在Python中使用循环创建列表 [英] Creating lists with loops in Python

查看:777
本文介绍了在Python中使用循环创建列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建具有不同变量名的列表序列,这些变量名对应于文本文件的不同行.我当前的代码要求我对文件中的行数进行硬编码:

I'm trying to create a sequence of lists with different variable names that correspond to different lines of a text file. My current code requires me to hard-code the number of lines in the file:

with open('ProjectEuler11Data.txt') as numbers:
    data = numbers.readlines()
    for line in data:
        if line == 1:
            line1 = line.split()
        if line == 2:
            line2 = line.split()
        if line == 3:
            line3 = line.split()
        if line == 4:
            line4 = line.split()

在这种情况下,我将不得不继续使用20个,这还不错,但是我想有一种我不知道的更简单的方法. 这是针对ProjectEuler的问题,但没有任何破坏者,而且我也在寻找有关此特定任务的建议,而不是我的整体策略.谢谢!

In this case, I would have to continue up to 20, which isn't that bad, but I imagine that there's an easier way that I'm not aware of. This is for a ProjectEuler problem, but there aren't any spoilers, and also I'm looking for advice on this specific task, rather than my strategy as a whole. Thanks!

推荐答案

with open('ProjectEuler11Data.txt') as numbers:
    data = numbers.readlines()
lines = [line.split() for line in data]

我不确定为什么可以在每行末尾都有一个数组的情况下为每行使用不同的变量名. 现在,您可以简单地按行[0],行[1]等访问单独的行.

I am not sure why you need different variable names for each line when you can have an array with all lines at the end. You can now simply access the individual lines by line[0], line[1] and so on.

这篇关于在Python中使用循环创建列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆