条'来自列表中的所有成员

发布于 2024-12-13 00:02:24 字数 351 浏览 1 评论 0原文

好的,所以我通过执行以下操作将文本文件中的每一行转换为列表的成员:
chkseq=[line.strip() for line in open("sequence.txt")]
因此,当我打印 chkseq 时,我得到:
['3','3']
我想要的是它看起来像这样: < br> [3,3]
我知道这是可能的,我只是不确定如何实现!我需要它们是整数,而不是字符串。因此,如果所有其他方法都失败了,这就是我的主要目标:从 .txt 文件创建一个列表,其成员是整数(这将是包含的所有 .txt 文件)。
谢谢!! -OSFTW

Ok, so I converted each line in a text file into a member of a list by doing the following:
chkseq=[line.strip() for line in open("sequence.txt")]
So when I print chkseq I get this:
['3','3']
What I would like is for it to instead look like this:
[3,3]
I know this is possible, I'm just unsure of how! I need them to be intergers, not strings. So if all else fails, that is my main goal in this: create a list from a .txt file whose members are intergers (which would be all the .txt file contained).
Thanks!! -OSFTW

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一片旧的回忆 2024-12-20 00:02:25

看起来您想将字符串解释为整数。使用 int 来执行此操作:

chkseq = [int(line) for line in open("sequence.txt")] 

也可以使用 map 而不是列表理解来编写:

chkseq = map(int, open("sequence.txt"))

It looks like you want to interpret the strings as integers. Use int to do this:

chkseq = [int(line) for line in open("sequence.txt")] 

It can also be written using map instead of a list comprehension:

chkseq = map(int, open("sequence.txt"))
屋檐 2024-12-20 00:02:25

迭代列表的元素并使用您喜欢的格式打印它们,而不是在一次打印整个列表时依赖默认格式。

iterate over the elements of your list and print them out with your preferred formatting rather than relying on the default formatting when printing the whole list at once.

难得心□动 2024-12-20 00:02:25

假设您的数组称为 input,并且您想要将值存储在名为 chkseq 的数组中,您的代码将是:

chkseq = [int(i) for i in input]

或者,如果您想在一行中完成所有操作:

chkseq = [int(i.strip()) for i in open("sequence.txt")]

Say your array is called input, and you want to store the value in an array called chkseq, your code would be:

chkseq = [int(i) for i in input]

Or, if you wanted to do everything all in one line:

chkseq = [int(i.strip()) for i in open("sequence.txt")]
葬シ愛 2024-12-20 00:02:25

将字符串传递给 int 构造函数将尝试将其转换为 int

>>> int('3')
3
>>> int('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'

Passing a string to the int constructor will attempt to turn it into a int.

>>> int('3')
3
>>> int('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文