[英]Python: Extract one value from a list of integers and lists
我有一個這樣的清單:
a = [3, 4, [1], 8, 9, [3, 4, 5]]
我想確定具有這些特征的列表何時只有一個值,然后將其提取到主列表中:
預期產量
a = [3, 4, 1, 8, 9, [3, 4, 5]]
我知道如何在由列表組成的列表中提取值,但是在這種情況下,我不知道如何
我的解決方案簡單明了:
result = []
for x in a:
if isinstance(x, list) and len(x) == 1: # check item type and length
result.append(x[0])
else:
result.append(x)
還是一樣但只有一行
>>> [x[0] if isinstance(x, list) and len(x) == 1 else x for x in a]
[3, 4, 1, 8, 9, [3, 4, 5]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.