您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

尝试将带有数字的txt文件读入列表,然后使用Python进行排序

尝试将带有数字的txt文件读入列表,然后使用Python进行排序

.readlines()会执行以下操作:逐行读取文件。在您的示例中,只有一行,因此长度为1。

在这一行中,您需要分割逗号:

with open(file1.txt,'r') as myfile:
    for line in myfile:
        print sorted(map(int, line.split(',')))

或者,如果您有多行包含大量数字:

data = []
with open(file1.txt,'r') as myfile:
    for line in myfile:
        data.extend(map(int, line.split(',')))
print sorted(data)

在这里,我使用withwith关键字来打开文件,可以逐行对其进行迭代。然后,在每一行上使用字符串的split方法,该方法将返回字符串列表。然后,我通过将int类型转换函数应用于列表中的每个项目,使用map将这些字符串转换为整数。然后可以对该列表进行排序。确保查看Python文档上的字符串方法页面

没有输入文件的测试:

numbers = "10,45,69,85,21,7,32,11,71,20,30"
data = []
data.extend(map(int, numbers.split(',')))
print sorted(data)

版画

[7, 10, 11, 20, 21, 30, 32, 45, 69, 71, 85]
python 2022/1/1 18:42:27 有479人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶