我有一个像这样的元组列表:
[('1001794', 'Us/Eastern', '2', '1', '3', '4', '5')
('1001832', 'Us/Central', '2', '3', '4', '4', '5')
('1001848', 'Us/Central', '2', '4', '5', '4', '5')
('1001855', 'Us/Central', '2', '1', '4', '4', '5')
('1001899', 'Us/Central', '2', '1', '4', '3', '5')
('1001914', 'Us/Pacific', '1', '4', '2', '4', '5')
('1001971', 'Us/Pacific', '3', '4', '2', '3', '5')
('1002021', 'Us/Eastern', '2', '1', '4', '4', '5')
('1002026', 'Us/Central', '2', '1', '4', '4', '2')
('1002028', 'Us/Eastern', '2', '1', '4', '4', '5')
('1002041', 'Us/Eastern', '2', '4', '3', '5', '4')]
我需要将那里的所有数字转换成数字。我不介意如果必要的话我是否必须做6种不同的列表理解,但我仍然不能完全理解列表理解,从头开始正确地制作一个。我试过做:
[x = (int(x[0]),x[1],int(x[2]),int(x[3]),int(x[4]),int(x[5]),int(x[6])) for x in tlist]
但它告诉我这是无效的语法,我不知道为什么?
使用str.isdigit
:
[tuple(int(y) if y.isdigit() else y for y in x) for x in tup]
# [(1001794, 'Us/Eastern', 2, 1, 3, 4, 5), ...]
这假设你的字符串中的数字是整数。 tup
是您的数据结构。
要处理负整数,请使用封装try-except
块的函数(阅读有关EAFP principle的信息):
def try_convert(s):
try:
return int(s)
except ValueError:
return s
[tuple(try_convert(y) for y in x) for x in tup]
# [(1001794, 'Us/Eastern', 2, 1, 3, 4, 5), ...]
要处理int
s和float
s,您可以使用嵌套块:
def try_convert(s):
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
return s
这对我有用:
y = [('1001794', 'Us/Eastern', '2', '1', '3', '4', '5'),
('1002041', 'Us/Eastern', '2', '4', '3', '5', '4')]
x = [(int(x[0]),x[1],int(x[2]),int(x[3]),int(x[4]),int(x[5]),int(x[6])) for x in y]
print(x)
[(1001794, 'Us/Eastern', 2, 1, 3, 4, 5), (1002041, 'Us/Eastern', 2, 4, 3, 5, 4)]
你只需要在x =
外面的[
。
如果你知道ints
在哪里,你可以使用Extended Iterable Unpacking
来简化你尝试使用的列表理解:
[(int(x), y, *map(int,v)) for x, y, *v in l]
[(1001794, 'Us/Eastern', 2, 1, 3, 4, 5),
(1001832, 'Us/Central', 2, 3, 4, 4, 5),
(1001848, 'Us/Central', 2, 4, 5, 4, 5),
(1001855, 'Us/Central', 2, 1, 4, 4, 5),
(1001899, 'Us/Central', 2, 1, 4, 3, 5),
(1001914, 'Us/Pacific', 1, 4, 2, 4, 5),
(1001971, 'Us/Pacific', 3, 4, 2, 3, 5),
(1002021, 'Us/Eastern', 2, 1, 4, 4, 5),
(1002026, 'Us/Central', 2, 1, 4, 4, 2),
(1002028, 'Us/Eastern', 2, 1, 4, 4, 5),
(1002041, 'Us/Eastern', 2, 4, 3, 5, 4)]
这是你看的答案吗?
list = []
newList = []
list = [
('1001794', 'Us/Eastern', '2', '1', '3', '4', '5'),
('1001832', 'Us/Central', '2', '3', '4', '4', '5'),
('1001848', 'Us/Central', '2', '4', '5', '4', '5'),
('1001855', 'Us/Central', '2', '1', '4', '4', '5'),
('1001899', 'Us/Central', '2', '1', '4', '3', '5'),
('1001914', 'Us/Pacific', '1', '4', '2', '4', '5'),
('1001971', 'Us/Pacific', '3', '4', '2', '3', '5'),
('1002021', 'Us/Eastern', '2', '1', '4', '4', '5'),
('1002026', 'Us/Central', '2', '1', '4', '4', '2'),
('1002028', 'Us/Eastern', '2', '1', '4', '4', '5'),
('1002041', 'Us/Eastern', '2', '4', '3', '5', '4')
]
newList = [[int(x[0]), x[1], int(x[2]), int(x[3]), int(x[4]), int(x[5]), int(x[6])] for x in list]
print(newList)