繁体   English   中英

Python:从整数和列表中提取一个值

[英]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.

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