我有一个list
strings
,其中包含sublist
操作系strings
:
ids = [u'spotify:track:3ftnDaaL02tMeOZBunIwls', u'spotify:track:4CKjTXDDWIrS0cwSA9scgk', [u'spotify:track:6oRbm1KOqskLTFc1rvGi5F',
u'spotify:track:045sp2JToyTaaKyXkGejPy']]
我试图用它来压扁它:
[item for item in ids for item in sublist]
和
chain = itertools.chain(ids)
但这些解决方案将字符串分开......
如何将原始list
展平为
[u'spotify:track:3ftnDaaL02tMeOZBunIwls', u'spotify:track:4CKjTXDDWIrS0cwSA9scgk', u'spotify:track:6oRbm1KOqskLTFc1rvGi5F',u'spotify:track:045sp2JToyTaaKyXkGejPy']
答案 0 :(得分:2)
您可以使用带isinstance
检查的简单循环。
out = []
for i in ids:
if isinstance(i, list):
out.extend(i)
else:
out.append(i)
print(out)
输出:
['spotify:track:3ftnDaaL02tMeOZBunIwls',
'spotify:track:4CKjTXDDWIrS0cwSA9scgk',
'spotify:track:6oRbm1KOqskLTFc1rvGi5F',
'spotify:track:045sp2JToyTaaKyXkGejPy']
您也可以使用itertools.chain
,但需要额外的预处理层:
from itertools import chain
out = list(chain.from_iterable([i if isinstance(i, list) else [i] for i in ids]))
print(out)
输出相同。
答案 1 :(得分:0)
您只需要将任何字符串转换为列表:
import itertools
ids = [u'spotify:track:3ftnDaaL02tMeOZBunIwls', u'spotify:track:4CKjTXDDWIrS0cwSA9scgk', [u'spotify:track:6oRbm1KOqskLTFc1rvGi5F',
u'spotify:track:045sp2JToyTaaKyXkGejPy']]
new_data = list(itertools.chain.from_iterable([[i] if not isinstance(i, list) else i for i in b]))
输出:
[u'spotify:track:3ftnDaaL02tMeOZBunIwls', u'spotify:track:4CKjTXDDWIrS0cwSA9scgk', u'spotify:track:6oRbm1KOqskLTFc1rvGi5F', u'spotify:track:045sp2JToyTaaKyXkGejPy']
答案 2 :(得分:0)
您可以创建一个功能来展平列表。
def flatten(lst):
if isinstance(lst, (str, unicode)):
return [lst]
return [unit for item in lst for unit in flatten(item)]
print(flatten(ids))
答案 3 :(得分:0)
你可以这样做:
>>> [x for l in ids for x in (l if isinstance(l, list) else [l])]
[u'spotify:track:3ftnDaaL02tMeOZBunIwls', u'spotify:track:4CKjTXDDWIrS0cwSA9scgk', u'spotify:track:6oRbm1KOqskLTFc1rvGi5F', u'spotify:track:045sp2JToyTaaKyXkGejPy']
这类似于您对[item for item in ids for item in sublist]
的列表理解,但添加了一个测试,看它是否实际上是我们正在查看的列表。