[英]Turning a list into a list of lists Python 3
I have a list file made up of car details. 我有一个包含汽车详细信息的列表文件。
eg 例如
1000001 Volvo v8
1000002 Mazda 2.0
It sounds like you need to split
each line; 听起来您需要
split
每行; you can use a list comprehension, as follows 您可以使用列表推导,如下所示
cars = [line.split() for line in open("Cars.txt")]
As mentioned in the comments; 如评论中所述; you want numerical representations of the numbers.
您需要数字的数字表示。 To do this you need to convert the numerical columns into numbers.
为此,您需要将数字列转换为数字。 Eg
例如
for i in range(len(cars)):
cars[i][0] = int(cars[i][0])
cars[i][-1] = int(cars[i][-1])
Then eg cars[0][0]
will be a number. 然后,例如
cars[0][0]
将是一个数字。 Alternatively, if the numbers will always be positive integers, you can condense this to: 或者,如果数字始终为正整数,则可以将其压缩为:
readline = lambda l: [int(n) if n.isdigit() else n for n in l.split()]
cars = [[ readline(line) for line in open("Cars.txt")]
For any more complicated datafile reading, you might want to use eg pandas
. 对于任何更复杂的数据文件读取,您可能想要使用例如
pandas
。
Generators 发电机
As pointed out by zondo in the comments, you might consider using a generator
instead, which doesn't load all the data into memory (instead "generating" each element when requested); 正如zondo在评论中指出的那样,您可以考虑使用
generator
,该generator
不会将所有数据加载到内存中(而是在请求时“生成”每个元素); this can be done by swapping []
for ()
in the comprehension: 这可以通过在理解中将
[]
换成()
来完成:
cars = (line.split() for line in open("Cars.txt"))
Then you can still iterate over cars as you would a list, but you can't index into a generator, as you can a list. 然后,您仍然可以像列表一样遍历汽车,但是不能像列表一样索引到生成器中。
If you want a proper way to access all the information in the text file, you can simply define a class for it. 如果您想以适当的方式访问文本文件中的所有信息,则只需为其定义一个类。 And later fill it with information from the file.
然后用文件中的信息填充它。 Here is an example implementation.
这是一个示例实现。 I used unpack operator (*) here.
我在这里使用了拆包运算符 (*)。
class Car(object):
def __init__(self, id, name, price):
self.id = id
self.name = name
self.price = price
def __str__(self):
return self.id + ' ' + self.name + ' ' + self.price
file = open("file.txt", 'r')
cars = [Car(*line.split()) for line in file]
for c in cars:
print c
Or use generator expression if you have a really large file 如果文件很大,也可以使用生成器表达式
cars = (Car(*line.split()) for line in file)
In both cases it prints, 在两种情况下都可以打印,
1000001 Volvo 34000
1000002 Mazda 23000
This is how you can store your results in a list
, using the split
function: 这是使用
split
函数将结果存储在list
中的方式:
cars = []
with open("cars.txt", 'r') as f:
for line in f:
cars.append(line.split())
If you want to be able to search quickly based on your unique ID, you might be better off using a dictionary. 如果您希望能够根据自己的唯一ID快速搜索,那么最好使用字典。
Here is a pure python way: 这是纯python方式:
text = '1000001 Volvo 34000 1000002 Mazda 23000'
# Split text into one list
l = text.split()
# Split list into list of list every 3rd element
l = [l[i:i+3] for i in range(0, len(l), 3)]
print l
[['1000001', 'Volvo', '34000'], ['1000002', 'Mazda', '23000']]
This could be done with a regex
to produce a list
of tuple
s: 可以使用
regex
来生成tuple
list
:
import re
text = '1000001 Volvo 34000 1000002 Mazda 23000'
l = re.findall(r'(\d+) (\w+) (\d+)', text)
print l
[('1000001', 'Volvo', '34000'), ('1000002', 'Mazda', '23000')]
If you really need a list
of list
s you can convert it: 如果您确实需要
list
的list
,则可以将其转换:
l = [list(x) for x in l]
print l
[['1000001', 'Volvo', '34000'], ['1000002', 'Mazda', '23000']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.