gpt4 book ai didi

python - 合并来自 2 个文本文件的列表

转载 作者:太空宇宙 更新时间:2023-11-04 02:12:45 25 4
gpt4 key购买 nike

我是 Python 的新手。我想获取 2 个文本文件的内容,将它们转换成 2 个列表,将它们合并在一起并从小到大排序。

将它们转换为列表似乎很容易,但我无法正确合并排序。

结果是这样的(列表的列表而不是单个列表): ['[0, 4, 6, 6, 22, 23, 44]', '[1, 4, 5, 6, 7, 22, 777]']

这是我的代码:

with open('numbers1.txt','r') as newfile1:
list1 = newfile1.read().splitlines()
print (list1)

with open('numbers2.txt','r') as newfile2:
list2 = newfile2.read().splitlines()
print (list2)

merged = []
for i in range(0, len(list1)) :
merged.append(list1[i])
merged.append(list2[i])
print(merged)

在此先感谢您的帮助。

最佳答案

首先,要加入列表,您可以使用简单的 + 运算符:

>>> l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]
>>> merged = l1 + l2
>>> print(merged)
[1, 2, 3, 4, 5, 6]

现在使用内置的 python 进行排序 sort()功能:

Python lists have a built-in list.sort() method that modifies the list in-place. By default, sort() doesn't require any extra parameters. However, it has two optional parameters:

reverse - If true, the sorted list is reversed (or sorted in Descending order)

key - function that serves as a key for the sort comparison

>>> l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]
>>> merged = l2 + l1
>>> print(merged)
[4, 5, 6, 1, 2, 3]
>>> merged.sort(key=int)
>>> print(merged)
[1, 2, 3, 4, 5, 6]

编辑

@Murray 上述解决方案工作得很好,但它不适合您的用例,因为在您的文本文件中您列出了类似的字符串:

This is numbers1.txt: [0, 4, 6, 6, 22, 23, 44] and this is numbers2.txt: [1, 4, 5, 6, 7, 22, 777] – Murray 1 hour ago

现在,当您将文件读取为 list1/list2 时,实际上您会得到一个包含一个元素的列表,该元素是一个字符串。

>>> with open("numbers1.txt", "r") as f:
... print(list1)
... print(type(list1))
... print(len(list1))
... print(type(list1[0]))
...
['[0, 4, 6, 6, 22, 23, 44]']
<type 'list'>
1
<type 'str'>

为了从文件中附加这些数字,您需要先解析它们。它可以像这样实现(取决于您的具体用例,最终解决方案可能会有所不同):

$ cat numbers1.txt 
[0, 4, 6, 6, 22, 23, 44]
$ cat numbers2.txt
[1, 4, 5, 6, 7, 22, 777]
$ cat test.py
files = ['numbers1.txt', 'numbers2.txt']
merged = []

for f in files:
with open(f,'r') as lines:
for line in lines:
for num in line.rstrip().strip('[]').split(', '):
merged.append(int(num))

print(merged)
merged.sort()
print(merged)
$ python test.py
[0, 4, 6, 6, 22, 23, 44, 1, 4, 5, 6, 7, 22, 777]
[0, 1, 4, 4, 5, 6, 6, 6, 7, 22, 22, 23, 44, 777]
$ python3 test.py
[0, 4, 6, 6, 22, 23, 44, 1, 4, 5, 6, 7, 22, 777]
[0, 1, 4, 4, 5, 6, 6, 6, 7, 22, 22, 23, 44, 777]

现在让我把这段代码分解成几个部分:

  1. 首先打开文件。我已经用 for 循环完成了它,所以每次我想打开一些东西时我都不必重复 with open...(它更容易,代码更易读)。
  2. 读取文件中的所有行。 (我假设你的文件可以有不止一行的字符串列表)
  3. 解析每一行并附加到列表中。
    • line.rstrip() - 删除结尾的换行符
    • .strip('[]') - 从字符串中删除方括号
    • .split(', ') - 用逗号和空格分割字符串以获得字符串字符数组
    • merged.append(int(num)) 将每个字符解析为 int 并附加到列表。
  4. 最后但并非最不重要的排序列表。

关于python - 合并来自 2 个文本文件的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53374965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com