[英]How to change string to Integers in python
试图从数字附近删除单引号。 我正在处理输入错误的第三部分数据。
lst = [ ('text','2','3','4'), ('text2','4','5','6') ]
y= [map(int,i) for i in zip(*lst)[1:]]
d = zip(*list)[0]
print d
c= zip(*y)
print c
dd = zip(d,c)
print dd
这就是结果:
('text', 'text2')
[(2, 3, 4), (4, 5, 6)]
[('text', (2, 3, 4)), ('text2', (4, 5, 6))]
如何得到:
dd = [ ('text',2,3,4), ('text2',4,5,6) ]
编辑:如果列表有时是这样的: [ ['text','2','3','4'], ['text2','4','5','6'] ]
,那么我该怎么办做? 另一个问题是整数“ 3,400”。
新的Lst示例:
lst = [ ('text','2','3','4'), ('text2','4','5,000','6,500') ]
需要:
[ ('text',2,3,4), ('text2',4,5000,6500) ]
print [(text, int(a), int(b), int(c)) for (text, a, b, c) in lst]
Jochen的答案适合您的具体情况。
如果由于某种原因需要将类型列表作为参数,则可以执行以下操作:
>>> lst = [ ('text','2','3','4'), ('text2','4','5','6') ]
>>> def map_rows(types, rows):
... return [tuple(f(x) for f, x in zip(types, row)) for row in rows]
>>> map_rows((str, int, int, int), lst)
[('text', 2, 3, 4), ('text2', 4, 5, 6)]
map_rows
定义的map_rows
是标准map
函数的一个表亲。 请注意,“类型”实际上是一个可调用序列,可以以您想要的任何方式“转换”值。
lst = [('text','2','3','4'), ('text2','4','5','6')]
dd = []
for t in lst:
new_tuple = []
for i in t:
try:
new_tuple.append(int(i))
except ValueError:
new_tuple.append(i)
dd.append(tuple(new_tuple))
lst = [ ('text','2','3','4'), ('text2','4','5','6') ]
new_lst = []
for tup in lst:
tmp = []
for index, item in enumerate(tup):
if index != 0:
tmp.append(int(item))
else:
tmp.append(item)
new_lst.append(tuple(tmp))
print new_lst
这可能不是执行此操作的pythonic方法:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.