简体   繁体   English

在 Python 中将字符串转换为列表

[英]Converting a string into a list in Python

I have a text document that contains a list of numbers and I want to convert it to a list.我有一个包含数字列表的文本文档,我想将其转换为列表。 Right now I can only get the entire list in the 0th entry of the list, but I want each number to be an element of a list.现在我只能在列表的第 0 个条目中获取整个列表,但我希望每个数字都是列表的一个元素。 Does anyone know of an easy way to do this in Python?有谁知道在 Python 中执行此操作的简单方法?

1000
2000
3000
4000

to

['1000','2000','3000','4000']

To convert a Python string into a list use the str.split method:要将 Python 字符串转换为列表,请使用str.split方法:

>>> '1000 2000 3000 4000'.split()
['1000', '2000', '3000', '4000']

split has some options: look them up for advanced uses. split有一些选项:查找它们以获取高级用途。

You can also read the file into a list with the readlines() method of a file object - it returns a list of lines.您还可以使用文件对象的readlines()方法将文件读入列表 - 它返回一个行列表。 For example, to get a list of integers from that file, you can do:例如,要从该文件中获取整数列表,您可以执行以下操作:

lst = map(int, open('filename.txt').readlines())

PS: See some other methods for doing the same in the comments. PS:在评论中查看其他一些执行相同操作的方法。 Some of those methods are nicer (more Pythonic) than mine其中一些方法比我的更好(更 Pythonic)

>>> open("myfile.txt").readlines()
>>> lines = open("myfile.txt").readlines()
>>> lines
['1000\n', '2000\n', '3000\n', '4000\n']
>>> clean_lines = [x.strip() for x in lines]
>>> clean_lines
['1000', '2000', '3000', '4000']

Or, if you have a string already, use str.split :或者,如果您已经有一个字符串,请使用str.split

>>> myfile
'1000\n2000\n3000\n4000\n'
>>> myfile.splitlines()
['1000', '2000', '3000', '4000', '']

You can remove the empty element with a list comprehension (or just a regular for loop)您可以使用列表理解(或只是常规for循环)删除空元素

>>> [x for x in myfile.splitlines() if x != ""]
['1000', '2000', '3000', '4000']
    $ cat > t.txt
    1
    2
    3
    4
    ^D
    $ python
    Python 2.6.1 (r261:67515, Jul  7 2009, 23:51:51) 
    [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> l = [l.strip() for l in open('t.txt')]
    >>> l
    ['1', '2', '3', '4']
    >>> 
   with open('file.txt', 'rb') as f:
       data = f.read()
   lines = [s.strip() for s in data.split('\n') if s]

You might need to strip newlines.您可能需要去除换行符。

# list of strings
[number for number in open("file.txt")]

# list of integers
[int(number) for number in open("file.txt")]

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

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