2

我认为这应该很容易,但我真的不知道如何以更好的方式编写它,如果你知道请告诉我

#there are some points in text files and was read into a list
s = ['3,4','4,5','6,5','7,8']
#break s element to (x,y) form every element should convert to number type
points = [] 
for pStr in s:
    ss = pStr.split(',')
    points.append([int(p) for p in ss])
print(points) #[[3, 4], [4, 5], [6, 5], [7, 8]]

请最好把它写在一行中

4

3 回答 3

6

使用列表理解:

In [19]: s = ['3,4','4,5','6,5','7,8']

In [21]: [[int(y) for y in x.split(',')] for x in s]
Out[21]: [[3, 4], [4, 5], [6, 5], [7, 8]]
于 2012-09-14T12:44:57.910 回答
5

如果使用 Python 2.x,您可以执行以下操作:

points = [map(int, x.split(',')) for x in s]

如果使用 Python 3.x,您需要将 map() 的结果传递给 list(),因为它返回一个迭代器:

points = [list(map(int, x.split(','))) for x in s]

在行动:

>>> s = ['3,4','4,5','6,5','7,8']
>>> points = [map(int, x.split(',')) for x in s]
>>> print(points)
[[3, 4], [4, 5], [6, 5], [7, 8]]
于 2012-09-14T12:42:10.290 回答
1
>>> s = ['3,4','4,5','6,5','7,8']
>>> from ast import literal_eval
>>> [literal_eval(x) for x in s]
[(3, 4), (4, 5), (6, 5), (7, 8)]

如果你真的需要列表列表

>>> [list(literal_eval(x)) for x in s]
[[3, 4], [4, 5], [6, 5], [7, 8]]
于 2012-09-14T12:55:47.377 回答