python - 如何进行嵌套列表理解 (Python)

标签 python list python-3.x dictionary list-comprehension

我有这本字典:

>>> times
{'time':[0,1,0], 'time_d':[0,1,0], 'time_up':[0,0,0]}

我想要这样的输出,值的顺序很重要!:

0 1 0 0 1 0 0 0 0
# 0 1 0 | 0 1 0 | 0 0 0     ===   time | time_d | time_up   items of the list

更准确地说,我想要一个这样的列表:

[0,1,0,0,1,0,0,0,0]

不使用print()

如果没有列表理解,我可以这样做:

tmp = []
for x in times.values():
    for y in x:
        tmp.append(y)

我尝试使用一些列表理解,但任何人都可以工作,就像这两个:

>>> [y for x in x for x in times.values()]
[0,0,0,0,0,0,0,0,0]

>>> [[y for x in x] for x in times.values()]
[[0,0,0],[0,0,0],[0,0,0]

如何用一行解决这个问题(列表理解)?

最佳答案

根据字典,您已经知道想要什么值,因此在制作列表时,请坚持明确地说明您希望从字典中获得什么值:

d = {'time':[0,1,0], 'time_d':[0,1,0], 'time_up':[0,0,0]}
v = [*d['time'], *d['time_d'], *d['time_up']]
print(v)

输出:

[0, 1, 0, 0, 1, 0, 0, 0, 0]

关于python - 如何进行嵌套列表理解 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45250095/

相关文章:

python - 如何将 MATLAB 集成到 TensorFlow?

python - 将字符串列表转换为字典

c++ - 在 C++ 源文件中每个函数定义的开头添加一个宏调用

python - 将行 reshape 为 Pandas 数据框中的列

python - 如何在Python中生成至少20位小数的种子随机 float ?

Python Pandas - Groupby 并制作列值标题

python - 使用 gtk.FileChooserDialog 选择大量文件时的平台相关性能问题

python - 在没有单引号Python的情况下将数字文本文件读入列表

list - 不匹配 $mylist 的每个元素

python - 这些不同的字符串格式化调用有哪些优点?