Ste*_*veS 5 python list concatenation
我有以下变量:
a = [1, 2, 3]
b = "de" # <-- not a (usual) list !
c = 5 # <-- not a list !
d = [4, 5, 23, 11, 5]
e = ["dg", "kuku"]
Run Code Online (Sandbox Code Playgroud)
现在我想将所有内容连接a, b, c, d, e到一个列表:
[1, 2, 3, "de", 5, 4, 5, 23, 11, 5, "dg", "kuku"]
Run Code Online (Sandbox Code Playgroud)
我已经尝试过itertools.chain,但没有成功。请告知我如何进行串联?
chain与可迭代一起使用。您的意思是:连接这些列表和原始值。
我看到两个步骤:
def ensure_list(x):
if isinstance(x, list):
return x
return [x]
lists = map(ensure_list, (a, b, c, d, e))
concatenated = list(itertools.chain.from_iterable(lists))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
709 次 |
| 最近记录: |