Python 将列表中的列表更改为列表中的字符串
如何返回列表,使列表由字符串而不是列表组成 以下是我的尝试:Python 将列表中的列表更改为列表中的字符串,python,string,nested-lists,Python,String,Nested Lists,如何返回列表,使列表由字符串而不是列表组成 以下是我的尝试: def recipe(listofingredients): listofingredients = listofingredients newlist = [] newlist2 = [] for i in listofingredients: listofingredients = i.strip("\n") newlist.append(listofingred
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']
我的输出是:
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']
所需输出:
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()。使用
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
按默认值以空格分隔。以新行a结尾且内部没有空格的字符串将转换为一个元素列表:
>>>'12345\n'.split()
['12345']
>>> 'eggs 4\n'.split()
['eggs', '4']
内部带有空格的字符串拆分为两个元素的列表:
>>>'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]
您可以使用Python的方法来实现这一点。利用这种方法 现在结果将是
['12345', 'eggs', '4', '$0.50', 'flour', '5', '$2.00']
供进一步阅读
在您的代码中有很多非常复杂的东西。。。但要回答您的问题,请将
newlist2.append(newlist)
更改为newlist2.extend(newlist)
它对我来说不太合适:(谢谢您的建议!适用于您的示例数据。)。没有很好地工作是有点太模糊,无法改进我的解决方案谢谢仔细阅读你提出的问题非常有帮助!