[英]How to change string to Integers in python
Trying to remove single quotes from around numbers. 试图从数字附近删除单引号。 I'm working with third paty data that's not well typed.
我正在处理输入错误的第三部分数据。
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
this is what the out is: 这就是结果:
('text', 'text2')
[(2, 3, 4), (4, 5, 6)]
[('text', (2, 3, 4)), ('text2', (4, 5, 6))]
How Do I get: 如何得到:
dd = [ ('text',2,3,4), ('text2',4,5,6) ]
EDIT: If list is sometimes this: [ ['text','2','3','4'], ['text2','4','5','6'] ]
, then what do i do? 编辑:如果列表有时是这样的:
[ ['text','2','3','4'], ['text2','4','5','6'] ]
,那么我该怎么办做? Another problem is integer as '3,400'. 另一个问题是整数“ 3,400”。
New Lst example: 新的Lst示例:
lst = [ ('text','2','3','4'), ('text2','4','5,000','6,500') ]
Need: 需要:
[ ('text',2,3,4), ('text2',4,5000,6500) ]
print [(text, int(a), int(b), int(c)) for (text, a, b, c) in lst]
Jochen's answer is the right thing for your specific case. Jochen的答案适合您的具体情况。
If, for some reason, you need to take the list of types as a parameter you can do something like this: 如果由于某种原因需要将类型列表作为参数,则可以执行以下操作:
>>> 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)]
The map_rows
defined above is sort of a cousin of the standard map
function. map_rows
定义的map_rows
是标准map
函数的一个表亲。 Note that "types" is really a sequence of callables that "convert" the value in whatever way you want. 请注意,“类型”实际上是一个可调用序列,可以以您想要的任何方式“转换”值。
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
This is probably not the pythonic way of doing it :) 这可能不是执行此操作的pythonic方法:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.