[英]I have a list in which each element is a single number in a list. How do I extract the numbers?
I am a python beginner and I have a list.我是 python 初学者,我有一份清单。 It goes like this:
它是这样的:
my_list=[
{"first":"1"},
{"second": "2"},
{"third": "1"},
{"four": "5"},
{"five":"5"},
{"six":"9"},
{"seven":"7"}
]
I want to extract the single values of this list.我想提取此列表的单个值。 I wrote the following piece of code:
我写了以下代码:
values = []
for element in my_list:
val = list(element.values())
values.append(val)
print(values)
This is my output:这是我的 output:
[['1'], ['2'], ['1'], ['5'], ['5'], ['9'], ['7']]
I want only the value numbers to be in my list.我只希望值数字出现在我的列表中。 [1,2,1,5,5,9,7] How do I fix my code?
[1,2,1,5,5,9,7] 如何修复我的代码?
You are almost correct but list(element.values())
gives you a list, You don't want to append the list itself but the only item inside it.您几乎是正确的,但是
list(element.values())
给了您一个列表,您不想 append列表本身,而是其中的唯一项目。 So do a subscription:订阅也是如此:
values.append(val[0])
or you can use .extend()
instead of .append()
:或者您可以使用
.extend()
而不是.append()
:
values.extend(val)
If I were to write this, I would do one of these:如果我要写这篇文章,我会做以下其中一项:
print([list(d.values())[0] for d in my_list])
print([next(iter(d.values())) for d in my_list])
The .values()
return a dict_values object, which is an iterable and since you're converting it to a list, so you can extract the first index in order to get your desired format like this .values()
返回一个 dict_values object,这是一个可迭代的,因为你正在将它转换为一个列表,所以你可以提取第一个索引以获得你想要的格式,就像这样
values = []
for element in my_list:
val = list(element.values())[0]
values.append(val)
print(values)
You can do like this,你可以这样做,
In [1]: list(map(lambda x:list(x.values())[0], my_list))
Out[1]: ['1', '2', '1', '5', '5', '9', '7']
my_list=[
{"first":"1"},
{"second": "2"},
{"third": "1"},
{"four": "5"},
{"five":"5"},
{"six":"9"},
{"seven":"7"}
]
values = [int(element.popitem()[1]) for element
in my_list]
print(values)
When in doubt, simply pop
the (most recently added) item:如有疑问,只需
pop
(最近添加的)项目:
>>> my_list = [
... {"first": "1"},
... {"second": "2"},
... {"third": "1"},
... {"four": "5"},
... {"five": "5"},
... {"six": "9"},
... {"seven": "7"}
... ]
>>> [int(d.popitem()[1]) for d in my_list]
[1, 2, 1, 5, 5, 9, 7]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.