2011-12-13 72 views
4

我需要在Python中將字符串'(2,3,4),(1,6,7)'轉換爲元組列表[(2,3,4),(1,6,7)]。 我想分割每',',然後使用for循環,並追加每個元組到一個空的列表。但我不太清楚如何去做。 提示,任何人?將字符串轉換爲元組列表

+0

可能重複的[Python的轉換格式化的字符串列表](http://stackoverflow.com/questions/3622643/python-convert-formatted-string-to-list) – eumiro

回答

7
>>> list(ast.literal_eval('(2,3,4),(1,6,7)')) 
[(2, 3, 4), (1, 6, 7)] 
+0

+1即將發佈類似的解決方案,但包裝s引入[]並使用eval。這看起來好多了。 – soulcheck

+0

我想在沒有ast.literal_eval的情況下執行此操作。 –

+0

@Linus:爲什麼?... –

2

只是爲了完整性:soulcheck的解決方案,符合樓主的要求,以避免ast.literal_eval:

def str2tupleList(s): 
    return eval("[%s]" % s) 
2

沒有AST或EVAL:

def convert(in_str): 
    result = [] 
    current_tuple = [] 
    for token in result.split(","): 
     number = int(token.replace("(","").replace(")", "")) 
     current_tuple.append(number) 
     if ")" in token: 
      result.append(tuple(current_tuple)) 
      current_tuple = [] 
    return result 
相關問題