【问题标题】:How to make a nested list comprehension (Python)如何进行嵌套列表理解(Python)
【发布时间】:2017-12-28 05:44:52
【问题描述】:

我有这本词典:

>>> 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]

我怎样才能用一行来解决这个问题(列表理解)?

【问题讨论】:

  • 根据您的预期输出顺序是否重要?
  • 您不能保证使用dict...
  • 是的,但是如果订单确实很重要,那么也许是使用适当的密钥来获取该订单的问题。这就是提出这个问题的原因。
  • @idjaw,嗯,是的,因为完全符合我要写的结果:print('Time: {}:{}:{} / {}:{}:{} ({}:{}:{})'.format(INSERT HERE THE LIST COMPREHENSION))
  • 但是为了记录,你的 for 循环的等效列表理解只是 [y for x in times.values() for y in x],但请注意,这不能保证给出你想要的输出,因为你不能保证 a 的顺序字典。

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


【解决方案1】:

根据您的字典,您已经知道自己想要什么值,所以在制作列表时,请坚持明确了解您想要从字典中得到什么:

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]

【讨论】:

  • 你来了!非常感谢cmets!!!你的回答很棒是加分项
【解决方案2】:

如果我理解了这个问题,你必须取值,然后平:

编辑,用户 @juanpa.arrivillaga 和 @idjaw 我想我更好地理解了这个问题,如果订单很重要,所以你可以使用orderedDict:

import collections

times = collections.OrderedDict()

times['time'] = [0,1,0]
times['time_d'] = [0,1,0]
times['time_up'] = [0,0,0]

def get_values(dic):
  return [value for values in times.values() for value in values]


print(get_values(times))

现在,如果您更改 dict,结果会按顺序排列:

times['time_up2'] = [0,0,1]

get_values(times)

它给了我:

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

如果顺序无关紧要

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

def get_values(dic):
  return [value for values in times.values() for value in values]


print(get_values(times))

【讨论】:

  • 您不能保证所需输出的预期顺序。
  • @idjaw ?但是输出就像我想要的那样,有什么问题?对不起,我不擅长那些东西。
  • @EnderLook 因为字典不保证顺序
  • 例如,复制粘贴您的代码会在我的机器上提供[0, 1, 0, 0, 0, 0, 0, 1, 0]
  • @EnderLook 如果您不更改字典,则字典顺序不会更改。如果您更改列表在字典中 没关系。但是,您不能依赖此解决方案,因为字典本质上是无序的
【解决方案3】:

这也适用于 Python 2:

[x for k in 'time time_d time_up'.split() for x in times[k]]

【讨论】:

    【解决方案4】:

    keyvalue 从字典中取出,并将append 放入一个列表中。

    times={'time':[0,1,0], 'time_d':[0,1,0], 'time_up':[0,0,0]}
    aa=[]
    for key,value in times.iteritems():
        aa.append(value)
    bb = [item for sublist in aa for item in sublist] #Making a flat list out of list of lists in Python
    print bb
    

    输出:

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

    【讨论】:

      猜你喜欢
      • 2021-07-22
      • 2015-08-12
      • 2016-05-10
      • 2021-02-13
      • 2014-11-18
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多