2014-03-01 115 views
3

我有這個列表;將混合數據類型的元組列表轉換爲所有字符串

List=[(1, 'John', 129L, 37L), (2, 'Tom', 231L, 23L)] 

我想將它轉換成這樣的樣子;

OutputList = [('1', 'John', '129', '37'), ('2', 'Tom', '231', '23')] 

列表中的所有數據類型都將變成字符串。我試過[str(i) for i in List],但它沒有變成正確的。解決這個問題的正確方法是什麼?

我使用蟒2.7

+0

「並沒有變成權利」是沒有問題的一個有用的說明 – jonrsharpe

回答

6

使用nested list comprehensiongenerator expression內側):

>>> lst = [(1, 'John', 129L, 37L), (2, 'Tom', 231L, 23L)] 
>>> [tuple(str(x) for x in xs) for xs in lst] 
[('1', 'John', '129', '37'), ('2', 'Tom', '231', '23')] 

或代替發電機表達的使用map

>>> [tuple(map(str, xs)) for xs in lst] 
[('1', 'John', '129', '37'), ('2', 'Tom', '231', '23')] 

上面列表解析是相似以下嵌套for循環:

>>> result = [] 
>>> for xs in lst: 
...  temp = [] 
...  for x in xs: 
...   temp.append(str(x)) 
...  result.append(tuple(temp)) 
... 
>>> result 
[('1', 'John', '129', '37'), ('2', 'Tom', '231', '23')] 
+0

使用你的答案我剛剛嘗試嵌套地圖(僅用於學習目的) –

+1

@GrijeshChauhan,'lambda我:str(i)'在你的答案中可以用'str'替換。 – falsetru

+0

是的我試過了,什麼時候使用lambda或當我可以避免時背後的關鍵技巧是什麼。 –

1

你也可以使用這樣的:

>>> lst 
[(1, 'John', 129L, 37L), (2, 'Tom', 231L, 23L)] 
>>> map(lambda x: tuple(map(lambda i: str(i), x)), lst) 
[('1', 'John', '129', '37'), ('2', 'Tom', '231', '23')] 

編輯:替換lambda i: str(i)只是str在內部地圖:

>>> map(lambda t: tuple(map(str, t)), lst) 
[('1', 'John', '129', '37'), ('2', 'Tom', '231', '23')] 
相關問題