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

Changing lists inside a list to strings inside a list

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

这是我的尝试:

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','[=10=].50\n','flour 5\n','.00\n'])
print result

我的输出是这样的:

[['12345'], ['eggs', '4'], ['[=11=].50'], ['flour', '5'], ['.00']]

期望的输出:

['12345', 'eggs', '4', '[=12=].50', 'flour', '5', '.00']

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

使用extendsplit:

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

split 默认以白色 space 分割。末尾有新行且内部没有 space 的字符串将变成单元素列表:

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

内部带有 space 的字符串拆分为一个二元列表:

>>> '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]

您可以使用 Python 的方法来完成此操作。利用 list comprehension and strip() 方法。

recipes = ['12345\n','eggs 4\n','[=10=].50\n','flour 5\n','.00\n']
recipes = [recipe.split() for recipe in recipes]
print sum(recipes, [])

现在的结果是

['12345', 'eggs', '4', '[=11=].50', 'flour', '5', '.00']

进一步阅读