如何返回列表以使列表由字符串而不是列表组成?
以下是我的尝试:
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()。
答案 0 :(得分:1)
使用extend
和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]
答案 1 :(得分:1)
您可以使用Python的方式执行此操作。利用list comprehension和strip()方法。
recipes = ['12345\n','eggs 4\n','$0.50\n','flour 5\n','$2.00\n']
recipes = [recipe.split() for recipe in recipes]
print sum(recipes, [])
现在结果将是
['12345', 'eggs', '4', '$0.50', 'flour', '5', '$2.00']
进一步阅读 https://stackoverflow.com/a/716482/968442 https://stackoverflow.com/a/716489/968442