我是一名 Python 初学者,我有一份 list 。它是这样的:
my_list=[
{"first":"1"},
{"second": "2"},
{"third": "1"},
{"four": "5"},
{"five":"5"},
{"six":"9"},
{"seven":"7"}
]
我想提取这个列表的单个值。 我写了以下代码:
values = []
for element in my_list:
val = list(element.values())
values.append(val)
print(values)
这是我的输出:
[['1'], ['2'], ['1'], ['5'], ['5'], ['9'], ['7']]
我只希望值数字出现在我的列表中。 [1,2,1,5,5,9,7] 如何修复我的代码?
最佳答案
你几乎是正确的,但是 list(element.values())
给了你一个列表,你不想附加列表本身但是里面的唯一项目它。订阅也是如此:
values.append(val[0])
或者您可以使用 .extend()
代替 .append()
:
values.extend(val)
如果我要写这篇文章,我会做以下其中一项:
print([list(d.values())[0] for d in my_list])
print([next(iter(d.values())) for d in my_list])
https://stackoverflow.com/questions/73927076/