python - 将列表内的列表更改为列表内的字符串

标签 python string nested-lists

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

这是我的尝试:

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]

关于python - 将列表内的列表更改为列表内的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34191723/

相关文章:

python - 将字典列表转换为树

python - 如何获得最重要单词的 TF-IDF 分数?

python - 如何使用 urllib 下载整个网站?

python - 在python中生成除数数组

c# - 如何找到字符串中的最后一个字母并获取其索引?

string - 大小爆炸文件与字符串

python - 删除子列表重复项,包括反向

python - celery 中的导入错误

javascript - 在接受用户的答案之前,如何将我的问题显示到控制台?

python - 将项目列表列表转换为 pandas 中的虚拟对象