gpt4 book ai didi

python - 无法修复未对齐的结果

转载 作者:行者123 更新时间:2023-12-01 06:40:55 24 4
gpt4 key购买 nike

我正在尝试解析字典中某些项目的值并相应地打印它们。我确实解析了它们,但是当我尝试打印它们时,考虑到对齐,输出变得更丑陋。如何按照预期输出中显示的方式获得打印结果?

字典中的项目[缩减部分]:

dict_items = [{'factLabel': 'Mode', 'factValue': 'Single'},
{'factLabel': 'Year', 'factValue': '1973'},
{'factLabel': 'Condition', 'factValue': 'Forced'},
{'factLabel': 'Identity', 'factValue': None},
{'factLabel': 'Availability', 'factValue': 'Rare'},
{'factLabel': 'Earn', 'factValue': 'Private'}]

我尝试像下面这样有条​​件地解析不同键的值:

for elem in dict_items:
mode = elem['factValue'] if elem['factLabel']=="Mode" else ""
year = elem['factValue'] if elem['factLabel']=="Year" else ""
condition = elem['factValue'] if elem['factLabel']=="Condition" else ""
identity = elem['factValue'] if elem['factLabel']=="Identity" else ""
availability = elem['factValue'] if elem['factLabel']=="Availability" else ""
income = elem['factValue'] if elem['factLabel']=="Income" else ""
print(mode,year,condition,identity,availability,income)

我得到的结果:

Single     
1973
Forced
None
Rare

预期输出:

Single 1973 Forced None Rare 

最佳答案

有几种方法可以做到这一点,特别是当您打算将数据输出为 CSV 时。理想的解决方案将完全取决于您的用例的具体情况,更具体地说,取决于数据的格式。

如果我们收到有关数据来源以及您计划如何使用数据的更多信息,我将更新我的解决方案,

<小时/>
dict_items = [{'factLabel': 'Mode', 'factValue': 'Single'},
{'factLabel': 'Year', 'factValue': '1973'},
{'factLabel': 'Condition', 'factValue': 'Forced'},
{'factLabel': 'Identity', 'factValue': None},
{'factLabel': 'Availability', 'factValue': 'Rare'},
{'factLabel': 'Earn', 'factValue': 'Private'}]

vals = dict(curr.values() for curr in dict_items)

:

{'Mode': 'Single', 'Year': '1973', 'Condition': 'Forced', 'Identity': None, 'Availability': 'Rare', 'Earn': 'Private'}
<小时/>
dict_items = [{'factLabel': 'Mode', 'factValue': 'Single'},
{'factLabel': 'Year', 'factValue': '1973'},
{'factLabel': 'Condition', 'factValue': 'Forced'},
{'factLabel': 'Identity', 'factValue': None},
{'factLabel': 'Availability', 'factValue': 'Rare'},
{'factLabel': 'Earn', 'factValue': 'Private'}]

vals = {curr['factLabel']: curr['factValue'] for curr in dict_items}

:

{'Mode': 'Single', 'Year': '1973', 'Condition': 'Forced', 'Identity': None, 'Availability': 'Rare', 'Earn': 'Private'}

关于python - 无法修复未对齐的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59460301/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com