List Comprehension创建了太多级别的嵌套列表

use*_*044 1 python list-comprehension python-2.7

我将两个列表中的元素组合在一起,但是被拉入的元素本身就是一个子列表.我怎样才能把它列为清单的第[2]项?

我的代码:

list =  [["pineapple", 10], ["cherry", 20], ["Carrot", 13], ["plum", 12]]
list1 = [["pineapple", 'Fruit'], ["cherry", 'Fruit'],["Carrot", 'Vegetable'],["plum", 'Fruit'],["Pepper", 'Vegetable']]

list = [[v1[0], v1[1], [v2[1] for v2 in list1 if v2[0] == v1[0]]] for v1 in list]

print list
Run Code Online (Sandbox Code Playgroud)

我的输出:

[['pineapple', 10, ['Fruit']], ['cherry', 20, ['Fruit']], ['Carrot', 13, ['Vegetable']], ['plum', 12, ['Fruit']]]
Run Code Online (Sandbox Code Playgroud)

期望的输出:

[['pineapple', 10, 'Fruit'], ['cherry', 20, 'Fruit'], ['Carrot', 13, 'Vegetable'], ['plum', 12, 'Fruit']]
Run Code Online (Sandbox Code Playgroud)

pok*_*oke 5

您可以只为该内部列表推导添加索引访问器,因此您将获得该列表的第一个元素而不是整个列表:

#                                                     This part is new
#                                                            ???
>>> [[v1[0], v1[1], [v2[1] for v2 in list1 if v2[0] == v1[0]][0]] for v1 in list]
[['pineapple', 10, 'Fruit'], ['cherry', 20, 'Fruit'], ['Carrot', 13, 'Vegetable'], ['plum', 12, 'Fruit']]
Run Code Online (Sandbox Code Playgroud)

由于您基本上是在查找水果类别,因此您可以将其制作list1成字典.这允许您只需查找一个值,而无需遍历整个列表:

# to convert the existing `list1`
>>> categories = dict(list1)

# or specify it directly as a dictionary:
>>> categories = {'pineapple': 'Fruit', 'cherry': 'Fruit', 'Carrot': 'Vegetable', 'plum': 'Fruit', 'Pepper': 'Vegetable'}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用索引来查找类别.比如categories['pineapple']给你'Fruit'.所以你可以在你的列表理解中使用它:

>>> [[v1[0], v1[1], categories[v1[0]]] for v1 in list]
[['pineapple', 10, 'Fruit'], ['cherry', 20, 'Fruit'], ['Carrot', 13, 'Vegetable'], ['plum', 12, 'Fruit']]
Run Code Online (Sandbox Code Playgroud)

最后,请注意:您不应仅仅为变量命名list.首先,list是引用列表类型的内置变量,并且覆盖该变量的值可能会在以后引起很多混淆.其次,这实际上更重要,这些变量名称可以为您提供有关其内容的零信息.如果你恰当地命名它会更好,所以你知道它们包含什么以及它们用于什么.