列表字典对列表的理解

时间:2018-08-28 07:08:46

标签: python list-comprehension

我有一个字典-

out_i = get(paste0("gapminder", i))

我只想使用列表理解来实现此输出-

a = {'b': [1,2,3], 'c':[4,5,6]}

一个简单的for循环可通过-

完成
[['c', 4], ['c', 5], ['c', 6], ['b', 1], ['b', 2], ['b', 3]]

试图将其转换为列表理解,我做到了-

x = []
for k, v in a.iteritems():
    for i in v:
        x.append([k, i])

但是对我来说很奇怪,我得到了输出

[[k,i] for i in v for k, v in a.items()]

正确的列表理解应该是什么?为什么我的列表理解不起作用?

3 个答案:

答案 0 :(得分:3)

您应该首先获得k,v,然后遍历v:

a = {'b': [1,2,3], 'c':[4,5,6]}
print([[k,i] for k, v in a.items() for i in v])

输出:

[['c', 4], ['c', 5], ['c', 6], ['b', 1], ['b', 2], ['b', 3]]

注意:

[[k,i] for i in v for k, v in a.items()]中,当您尝试对其进行迭代时,未定义v

@Skam就是一个很好的例子:how to interpret double for loop comprehension

# Without list comprehension
list_of_words = []
for sentence in text:
    for word in sentence:
       list_of_words.append(word)
return list_of_words

等效于:

[word for sentence in text for word in sentence]

答案 1 :(得分:3)

您快到了。您面临的主要问题是由于for循环的顺序。

列表理解中for循环的顺序基于它们在传统循环方法中出现的顺序。最外面的循环先到,然后是内部循环。

a = {'b': [1,2,3], 'c':[4,5,6]}
x = []
for k, v in a.items():
    for i in v:
        x.append([k, i])

print(x)

print([[k,i] for i in v for k, v in a.items()])
print([[k,i] for k, v in a.items() for i in v])

输出

[['b', 1], ['b', 2], ['b', 3], ['c', 4], ['c', 5], ['c', 6]]
[['b', 4], ['c', 4], ['b', 5], ['c', 5], ['b', 6], ['c', 6]]
[['b', 1], ['b', 2], ['b', 3], ['c', 4], ['c', 5], ['c', 6]]

答案 2 :(得分:1)

您可以尝试使用itertools.product

from itertools import product, chain
a = {'b': [1,2,3], 'c':[4,5,6]}
list(chain(*[product(k, v) for k, v in a.items()]))

结果是

[('b', 1), ('b', 2), ('b', 3), ('c', 4), ('c', 5), ('c', 6)]

如果您非常需要列表列表,可以这样做

list(chain(*[[list(item) for item in product(k, v)] for k, v in a.items()]))

输出为:

[['b', 1], ['b', 2], ['b', 3], ['c', 4], ['c', 5], ['c', 6]]

和一些性能测试

In [6]: %timeit [[i, j] for i in a for j in a[i]]
618 ns ± 5.34 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [7]: %timeit list(chain(*[product(k, v) for k, v in a.items()]))
1.26 µs ± 19.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [8]: %timeit list(chain(*[[list(item) for item in product(k, v)] for k, v in a.items()]))
2.61 µs ± 49.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)