Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将长度为1的嵌套列表转换为字符串_Python_List - Fatal编程技术网

Python 将长度为1的嵌套列表转换为字符串

Python 将长度为1的嵌套列表转换为字符串,python,list,Python,List,我有一个Python列表,其中包含一些长度为1的嵌套列表: [['7746'],'12','1929','8827',['7'],'8837','128'] 我想去掉列表,只需将字符串保留在其中,就可以得到: ['7746'、'12'、'1929'、'8827'、'7'、'8837'、'128'] 如何执行此操作?您可以使用列表理解和三元条件: empty = [(x[0] if isinstance(x, list) else x) for x in nested] 或者,使用简单循环的明显

我有一个Python列表,其中包含一些长度为1的嵌套列表:

[['7746'],'12','1929','8827',['7'],'8837','128']

我想去掉列表,只需将字符串保留在其中,就可以得到:

['7746'、'12'、'1929'、'8827'、'7'、'8837'、'128']


如何执行此操作?

您可以使用列表理解和三元条件:

empty = [(x[0] if isinstance(x, list) else x) for x in nested]
或者,使用简单循环的明显解决方案:

empty = []
for x in nested:
    if isinstance(x, list):
        empty.append(x[0])
    else:
        empty.append(x)

你在用什么语言?Python。对不起,我没有提到。我一整天都在尝试for循环、range函数之类的东西。正如您所知,我对Python的了解非常有限。所以我能尝试的东西不多。。。我只是认为有一种快速的方法可以将长度为1的列表转换为普通字符串…嵌套=['7746']、['12'、['1929'、'8827']、['7']、['8837'、['128']]空=列表()用于范围内的内容(len(nested)):如果len(nested[stuff])>1:x=nested[stuff]用于x中的内容:empty.append(stuff)其他:empty.append(stuff)打印空这是我试过的一些代码。但问题是,对于长度为1的列表,我得到的是范围,而不是列表中的值。