简体   繁体   English

Python-从文本文件读取并放入列表

[英]Python - Read from text file and put into a list

As title, I have been trying to read text from file, convert to int and store it in a list. 作为标题,我一直在尝试从文件中读取文本,转换为int并将其存储在列表中。 My text file look like this: 我的文本文件如下所示:

1,2
3,4
5,6

I want to read this file, put each pair of numbers into a list m , and store those lists in a bigger list lis . 我想读取此文件,将每对数字放入列表m ,并将这些列表存储在更大的列表lis Here is my attempt: 这是我的尝试:

def read_file():        
    lis = []
    m = [0,0]

    with open("data.txt") as f:
        for line in f:
            m[0], m[1] = line.split(",")    # assign to list m
            m[0] = int(m[0])   # cut off '\n' and for later use
            m[1] = int(m[1])   
            lis.append(m)      # store in lis

    print lis

I expect the lis to be like this: 我希望lis是这样的:

[[1, 2], [3, 4], [5, 6]]

But instead, it is: 但是,它是:

[[5, 6], [5, 6], [5, 6]]

I have tried insert instead of append but it seems like that's not where it has problems. 我尝试insert而不是append但似乎那不是问题所在。 I need some help - thank you in advance! 我需要一些帮助-预先感谢您!

You are reusing the same list m in each iteration of the loop, each time overwriting the values set in the previous iteration. 您将在循环的每次迭代中重复使用同一列表m ,每次都覆盖前一次迭代中设置的值。 In the end, lis holds many references to the same list. 最后, lis拥有对同一列表的许多引用。

Instead, assign a new value to m as a whole in the loop: 而是在循环中为m 整体分配一个新值:

for line in f:
    m = [0,0]
    m[0], m[1] = line.split(",")
    m[0] = int(m[0])
    m[1] = int(m[1])   
    lis.append(m)

Or shorter: 或更短:

for line in f:
    m = line.split(",")
    m[0] = int(m[0])
    m[1] = int(m[1])   
    lis.append(m)

Or even shorter, using map: 甚至更短,使用map:

for line in f:
    m = list(map(int, line.split(",")))
    lis.append(m)

Or even more shorter, using a list comprehension: 甚至更短一些,使用列表推导:

lis = [list(map(int, line.split(","))) for line in f]
def read_file():        
    lis = []
    with open("data.txt") as f:
        for line in f:
            m, n = line.split(",")    
            lis.append([int(m), int(n)])      

    print lis

In lis all index reference to one list m . lis所有索引都引用一个列表m If any update in m is takes place, m is update every where 如果m中发生任何更新,则m在每个位置更新

在此处输入图片说明

Try this 尝试这个

lis.append( list(map(int,line.split(","))))    

Output 输出量

[['1', '2'], ['3', '4'], ['5', '6']] [['1','2'],['3','4'],['5','6']]

Use csv.reader object instead which uses , (comma) as default field separator: 使用csv.reader对象代替,该对象使用, (逗号)作为默认字段分隔符:

import csv

with open('data.txt') as f:
    reader = csv.reader(f)
    result = [list(map(int, lst)) for lst in reader]
    print(result)

The output: 输出:

[[1, 2], [3, 4], [5, 6]]

https://docs.python.org/3/library/csv.html?highlight=csv#csv.reader https://docs.python.org/3/library/csv.html?highlight=csv#csv.reader

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM