2011-04-03 86 views
1

我有一個變量x(列表),看起來像
的Python轉換成元組

['JACKIE:34', 'MATT:444', 'CEN:12', 'PETE:12', 'RANDY:92', 'MITCH:2', 'JAN:2'] 

然後我想轉換成元組(兩人一組),所以它看起來像
 
[('JACKIE',34), ('MATT',444), ('CEN',12), ('PETE',12), ('RANDY',92), ('MITCH',2), ('JAN',2)]

注意,號碼是INT。

+0

可能重複的[單獨的對象和把它們放進雙(http://stackoverflow.com/questions/5526040/separate-objects-and-放了他們,成爲對) – Johnsyweb 2011-04-03 05:30:18

回答

7

編號爲整數,所請求的

before = ['JACKIE:34', 'MATT:444', 'CEN:12', 'PETE:12', 'RANDY:92', 'MITCH:2', 'JAN:2'] 
after = [(name, int(value)) for name, value in (x.split(':') for x in before)] 
print after 
2
a = ['JACKIE:34', 'MATT:444', 'CEN:12', 'PETE:12', 'RANDY:92', 'MITCH:2', 'JAN:2'] 
b = [x.split(':') for x in a] 
b = [(x[0], int(x[1])) for x in b]