Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个这样的清单:
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]]