Skip to main content
 首页 » 编程设计

python之将列表中的列表更改为列表中的字符串

2024年10月24日26langtianya

如何返回我的列表,以便该列表由字符串而不是列表组成?

这是我的尝试:

def recipe(listofingredients): 
    listofingredients = listofingredients  
    newlist = [] 
    newlist2 = [] 
 
    for i in listofingredients: 
        listofingredients = i.strip("\n") 
        newlist.append(listofingredients) 
 
    for i in newlist: 
        newlist = i.split() 
        newlist2.append(newlist) 
    return newlist2 
 
result = recipe(['12345\n','eggs 4\n','$0.50\n','flour 5\n','$2.00\n']) 
print result 

我的输出是这样的:

[['12345'], ['eggs', '4'], ['$0.50'], ['flour', '5'], ['$2.00']] 

期望的输出:

['12345', 'eggs', '4', '$0.50', 'flour', '5', '$2.00'] 

我知道我的问题是将一个列表附加到另一个列表,但我不确定如何在列表以外的任何对象上使用 .strip() 和 .split()。

请您参考如下方法:

使用扩展和拆分:

>>> L = ['12345\n','eggs 4\n','$0.50\n','flour 5\n','$2.00\n'] 
>>> res = [] 
>>> for entry in L: 
        res.extend(entry.split()) 
>>> res 
['12345', 'eggs', '4', '$0.50', 'flour', '5', '$2.00'] 

split 默认在空格处拆分。以新行结尾且内部没有空格的字符串被转换为单元素列表:

>>>'12345\n'.split() 
['12345'] 

内部有空格的字符串拆分成一个双元素列表:

>>> 'eggs 4\n'.split() 
['eggs', '4'] 

extend() 方法有助于从其他列表构建列表:

>>> L = [] 
>>> L.extend([1, 2, 3]) 
>>> L 
[1, 2, 3] 
>>> L.extend([4, 5, 6]) 
L 
[1, 2, 3, 4, 5, 6]