>> a -6ren">
gpt4 book ai didi

python - 脱落列表层 - Python

转载 作者:太空宇宙 更新时间:2023-11-04 09:40:35 27 4
gpt4 key购买 nike

你怎么能转:

[[["hi"], ["hello"]]]

进入:

[["hi"], ["hello"]]

同时还使用 [] 作为输入

最佳答案

您可以使用pop 函数从列表中取出第一项。

>>> a = [["hi"]]
>>> a = a.pop(0)
>>> a
['hi']

或者你也可以这样做:

>>> a = [["hi"]]
>>> a = a[0]
>>> a
['hi']

在您编辑问题时:

>>> a = [[["hi"], ["hello"]]]
>>> a = a.pop(0)
>>> a
[['hi'], ['hello']]

如果你有一个空列表:

a = []
try:a = a.pop(0) #try if it don't raises an error
except:pass #if error is raised, ingnore it

因此,根据上面的代码,如果列表为空,则不会引发任何错误。

如果你想让它更简单:

a = []
if len(a) != 0:a = a[0]
print(a)

您还可以制作一个函数,使其易于使用空列表或非空列表:

def get(list):
return list if len(list) == 0 else list[0]

测试我们的功能:

>>> get([])
[]
>>> get([["Hi","Bye"]])
['Hi', 'Bye']

关于python - 脱落列表层 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51870897/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com