简体   繁体   English

PYTHON合并列表中的单个元素与子列表

[英]PYTHON-Merge single elements in list with sublist

I try to make flat list. 我尝试列出简单的清单。 Now I have list: 现在我有清单:

L=['aa',['bb','cc']]

and I try: 我尝试:

L=['aa',['bb','cc']]
new=[]

for i in L:
  print i
  new+=i

print new

and I got: 我得到:

'aa'

['bb','cc']

['a','a','bb','cc']

Why in print i=0 = 'aa' and in new+=ii=0 is only 'a'? 为什么在print i=0 = 'aa'而在new+=ii=0中仅是'a'?

How i could get list ['aa','bb','cc'] ? 我如何获得列表['aa','bb','cc']

In general, meaning when you don't know the depth of the original list, this should work: 通常,这意味着当您不知道原始列表的深度时,这应该可以工作:

L=['aa',['bb','cc', ['dd', 'ee']], 'ff']
new = []
for l_item in L:
    stack = [ l_item ]
    while stack:
        s_item = stack.pop(0)
        if isinstance(s_item, list):
            stack += [ x for x in s_item ]
        else:
            new.append(s_item)
print new 

This gives: 这给出:

['aa', 'bb', 'cc', 'dd', 'ee', 'ff']

Well, don't forget that strings are iterable in Python. 好吧,不要忘记字符串在Python中是可迭代的。

>>> new = []
>>> new += 'aa'
>>> print new
['a', 'a']

To be sure of adding what you want, you can proceed this way: 为了确保添加您想要的内容,可以按照以下方式进行:

>>> L = ['aa',['bb','cc']]
>>> new = []

>>> for e in L:
...     new.extend(e if type(e) == list else (e,))
>>> print new
['aa', 'bb', 'cc']

Seriously, 说真的


PS You can look at this post ... for more information. 附注:您可以查看此帖子...以获取更多信息。

This happens because you iterate over 'aa' , basically treating it like it was ['a', 'a'] . 发生这种情况是因为您对'aa'进行了迭代,基本上将其视为['a', 'a']对待。

If you want to avoid iterating over strings, you can look at the type: 如果要避免遍历字符串,可以查看类型:

for i in L:
    if isinstance(i, list):
        new += i
    else:
        new.append(i)

See this question for more details and how to do it recursively: 有关更多详细信息以及如何递归执行,请参见以下问题:

Flatten (an irregular) list of lists 拼合(不规则的)列表列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM