[英]python - Convert Single integer into a list
假設我有以下列表:
a = 1
b = [2,3]
c = [4,5,6]
我想連接它們,以便我得到以下內容:
[1,2,3,4,5,6]
我嘗試了通常的+
運算符:
>>> a+b+c
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
這是因為a
術語。 它只是一個整數。 所以我將所有內容轉換為列表:
>>> [a]+[b]+[c]
[1, [2, 3], [4, 5, 6]]
不完全是我要找的。
我也嘗試了這個答案中的所有選項,但我得到了與上面提到的相同的int
錯誤。
>>> l = [a]+[b]+[c]
>>> flat_list = [item for sublist in l for item in sublist]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
TypeError: 'int' object is not iterable
它應該足夠簡單,但沒有任何適用於該術語a
。 有沒有辦法有效地做到這一點? 它好好嘗試一下一定是Python的。
沒有什么,它會自動把一個int
,如果它是一個列表int
。 您需要檢查該值是否為列表:
(a if type(a) is list else [a]) + (b if type(b) is list else [b]) + (c if type(c) is list else [c])
如果您必須經常這樣做,您可能需要編寫一個函數:
def as_list(x):
if type(x) is list:
return x
else:
return [x]
然后你可以寫:
as_list(a) + as_list(b) + as_list(c)
您可以使用itertools
:
from itertools import chain
a = 1
b = [2,3]
c = [4,5,6]
final_list = list(chain.from_iterable([[a], b, c]))
輸出:
[1, 2, 3, 4, 5, 6]
但是,如果您事先不知道a
、 b
和c
的內容,則可以嘗試以下操作:
new_list = [[i] if not isinstance(i, list) else i for i in [a, b, c]]
final_list = list(chain.from_iterable(new_list))
接受的答案是最好的方法。 添加另一個變體。 評論中也有解釋。
from collections.abc import Iterable
a = "fun"
b = [2,3]
c = [4,5,6]
def flatten(lst):
for item in lst:
if isinstance(item,Iterable) and not isinstance(item,str): # checking if Iterable and taking care of strings as well
yield from flatten(item)
else:
yield item
# test case:
res = []
res.extend([a]+[b]+[c]) # casting them into lists, [a]+[b]+[c] [1, [2, 3], [4, 5, 6]]
print(list(flatten(res)))
生產
['fun', 2, 3, 4, 5, 6]
[Program finished]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.