【问题标题】:How to split lists at spaces Python如何在空格处拆分列表Python
【发布时间】:2016-02-16 02:37:23
【问题描述】:

这里是 Python 初学者。 我有一个函数应该打开两个文件,在空格处拆分它们,并将它们存储在列表中,以便在另一个函数中访问。 我的第一个函数类似于:

listinput1 = input("Enter the name of the first file that you want to open: ")
listinput2 = input("Enter the name of the first file that you want to open: ")
list1 = open(listinput1)
list1 = list(list1)
list2 = open(listinput2)
list2 = list(list2)
metrics = plag(list1, list2)
print(metrics)

但是当我执行第二个函数时,我看到列表没有像我预期的那样在空格处拆分。我已经尝试了 split 函数,并且我还尝试使用 for 循环来迭代列表的每个增量。

【问题讨论】:

  • list1 = list1.read().split()
  • @Boosted,按空格分割还是全部空格?
  • @PadraicCunningham 仅限空格。
  • @AvinashRaj 谢谢你,这很有帮助!

标签: python list split


【解决方案1】:

一些建议:

  • 当你open() 一个文件时,你也需要close() 它。您没有这样做(通常,单独执行不是一个好主意,因为如果程序首先遇到异常,可能会错过关闭)。

    这里首选的 Python 习语是with open(path) as f:

    with open(listinput1) as f:
       # do stuff with f
    

  • 当你调用open(listinput1) 时,你会得到一个文件对象。对此调用list() 将从文件中获取行列表,例如:

    # colours.txt
    amber
    blue
    crimson | dark green
    

    with open('colours.txt') as f:
        print(list(f))  # ['amber', 'blue', 'crimson | dark green']
    

    要从文件中获取包含文本的字符串,请在对象上调用read() 方法,然后对该字符串使用split() 方法。

    with open('colours.txt') as f:
        text = f.read()         #  'amber\nblue\ncrimson | dark green'
        print(text.split(' '))  # ['amber\nblue\ncrimson', '|', 'dark', 'green']
    

  • 您要求第一个文件两次。第二个字符串应该是“输入您要打开的第二个文件的名称”吗?

以下是包含这些更改的代码的更新版本:

path1 = input("Enter the name of the first file that you want to open: ")
path2 = input("Enter the name of the second file that you want to open: ")

with open(path1) as f1:
    list1 = f1.read().split(' ')

with open(path2) as f2:
    list2 = f2.read().split(' ')

【讨论】:

    猜你喜欢
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-26
    相关资源
    最近更新 更多