[英]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.