[英]How to make a list of numbers out of strings in a list of lists in Python
[英]How to get numbers out of this list of strings in python
我从文件中读取了python中的字符串列表:
lines = ['4 11', '8 4', '10 5', '15 8', '4 3']
如果我想将4和11分配给一些变量。 我做类似的事情:
a, b = lines[0][0], lines[0][2:]
现在,如果需要执行以下操作,则需要为某些变量分配10和5:
c, d = lines[2][0], lines[2][2:]
它给:
1
5
因此,我必须这样做:
f, g = lines[0][0:2], lines[0][3]
以获取列表中特定元素的所需结果。
我必须为任何输入文件自动执行此过程。 我究竟做错了什么? 有什么帮助吗?
您应该使用split()
而不是假设数字将是哪个字符。
for num_pair in lines:
a, b = lines.split() # Splits based on whitespace
# Do something with a and b
split()
将字符串分成较小的字符串列表,并根据空格进行拆分(或者,如果将字符作为参数传递,则在该字符上进行拆分)。
In [13]: lines = ['4 11', '8 4', '10 5', '15 8', '4 3']
In [14]: [[int(i) for i in line.split()] for line in lines]
Out[14]: [[4, 11], [8, 4], [10, 5], [15, 8], [4, 3]]
现在,您可以遍历新列表并分配所需的任何变量
编辑 :
如果只想读取每对数字一次,则可以将列表理解变成一个生成器(只需将外部[]
更改为()
)。 这样,并非所有结果都存储在列表中,您可以一次访问它们:
([int(i) for i in line.split()] for line in lines)
您可以使用地图:
lines = ['4 11', '8 4', '10 5', '15 8', '4 3']
a,b = map(int,lines[0].split())
print a,b
4 11
a, b, c, d = map(int,lines[0].split() + lines[2].split())
print a,b,c,d
4 11 10 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.