python-提取列表元素

时间:2018-08-15 08:29:34

标签: python python-3.x

我有一个像这样的列表。

[{0: 26},
 {0: 36},
 {1: 1},
 {0: 215},
 {1: 63},
 {0: 215}]

如何提取仅包含的另一个列表。 [0,0,1,0,1,0]

8 个答案:

答案 0 :(得分:4)

使用dict.keys提取每个字典的键,转换为列表,然后提取第一个元素

>>> lst = [{0: 26}, {0: 36}, {1: 1}, {0: 215}, {1: 63}, {0: 215}]
>>> [list(d.keys())[0] for d in lst]
[0, 0, 1, 0, 1, 0]

或者,您可以使用以下列表理解

>>> [k for d in lst for k in d.keys()]
[0, 0, 1, 0, 1, 0]

答案 1 :(得分:4)

使用dict.keys()从字典中获取键,并将其用于列表理解中,如下所示:

lst = [{0: 26},
       {0: 36},
       {1: 1},
       {0: 215},
       {1: 63},
       {0: 215}]

print([y for x in lst for y in x.keys()])
# [0, 0, 1, 0, 1, 0]

或者,这应该进一步简化为:

print([y for x in lst for y in x])

因为,当您像for y in x这样简单地遍历字典时,实际上是在遍历字典的键。

答案 2 :(得分:2)

我建议您简单地遍历词典列表,并使用如下列表理解遍历每本词典的键:

myList = [{0: 26}, {0: 36}, {1: 1}, {0: 215}, {1: 63}, {0: 215}]
newList = [k for d in myList for k in d]
print(newList) # [0, 0, 1, 0, 1, 0]

答案 3 :(得分:1)

这些是键,因此您将使用dict.keys()方法:

L = [{0: 26},
     {0: 36},
     {1: 1},
     {0: 215},
     {1: 63},
     {0: 215}]

L2 = [list(d.keys())[0] for d in L]

答案 4 :(得分:1)

使用dict()的keys()函数。

a = [{0: 26}, {0: 36}, {1: 1}, {0: 215}, {1: 63}, {0: 215}]
keys = list(a.keys()[0])
vaues = (a.values()[0]) 

干杯!

答案 5 :(得分:1)

您可以这样:

list = [list(d.keys())[0] for d in originalList] #  originalList is the first list you posted

以下是输出:[0,0,1,0,1,0]

答案 6 :(得分:1)

您可以使用dict.keysitertools.chain构建所有密钥的列表:

from itertools import chain

w = [{0: 26},
   {0: 36},
   {1: 1},
   {0: 215},
   {1: 63},
   {0: 215}]

keys = list(chain.from_iterable(map(dict.keys, w)))

答案 7 :(得分:1)

或使用map尝试以下代码:

lod=[{0: 26},
 {0: 36},
 {1: 1},
 {0: 215},
 {1: 63},
 {0: 215}]
print(list(map(lambda x: list(x.keys())[0])))