2012-10-11 21 views
350

我試圖將列表轉換爲元組。在Python中將列表轉換爲元組

當我谷歌,我找了很多類似的答案:

l = [4,5,6] 
tuple(l) 

但如果我這樣做,我收到此錯誤信息:

TypeError: 'tuple' object is not callable

我怎樣才能解決這個問題?

+51

你在別處之前分配變量名'tuple'? – eumiro

+8

不要太過挑剔,但你可能也不應該使用小寫「el」作爲變量名稱,因爲它與1相似。由於其類似於零,因此大寫「哦」也是如此。即使是「李」比較也更具可讀性。 –

回答

521

它應該工作正常。請勿使用tuplelist或其他特殊名稱作爲變量名稱。這可能是什麼導致你的問題。

>>> l = [4,5,6] 
>>> tuple(l) 
(4, 5, 6) 
+0

工程就像一個魅力! – Linjie

86

擴展在eumiro的評論,通常tuple(l)將列表l轉換成一個元組:

In [1]: l = [4,5,6] 

In [2]: tuple 
Out[2]: <type 'tuple'> 

In [3]: tuple(l) 
Out[3]: (4, 5, 6) 

但是,如果你重新定義tuple是一個元組,而不是typetuple

In [4]: tuple = tuple(l) 

In [5]: tuple 
Out[5]: (4, 5, 6) 

然後你得到一個TypeError,因爲元組本身不可調用:

In [6]: tuple(l) 
TypeError: 'tuple' object is not callable 

您可以通過退出並重新啓動你的解釋,或(感謝@glglgl)恢復原始定義tuple

In [6]: del tuple 

In [7]: tuple 
Out[7]: <type 'tuple'> 
+16

你應該可以用一個簡單的del元組來恢復。 – glglgl

+1

謝謝,@glglgl。我不知道,儘管事後看來這很有道理。 – unutbu

+0

謝謝@glglgl重新設置我的元組工作奇蹟:-) 並感謝unutbu張貼 – Alvis

23

你可能會做這樣的事情:

>>> tuple = 45, 34 # You used `tuple` as a variable here 
>>> tuple 
(45, 34) 
>>> l = [4, 5, 6] 
>>> tuple(l) # Will try to invoke the variable `tuple` rather than tuple type. 

Traceback (most recent call last): 
    File "<pyshell#10>", line 1, in <module> 
    tuple(l) 
TypeError: 'tuple' object is not callable 
>>> 
>>> del tuple # You can delete the object tuple created earlier to make it work 
>>> tuple(l) 
(4, 5, 6) 

問題出在這裏......既然你已經使用了一個tuple變量來保存tuple (45, 34) ......因此,現在tuple是一個object類型tuple現在...

它不再是type因此,它不再是Callable

Never使用任何內置類型作爲變量名稱...您可以使用任何其他名稱。使用任意名稱爲您的變量,而不是...

10
l = [4,5,6] 

到列表轉換爲元組,

l = tuple(l) 
3

我找到很多答案最新和適當回答的問題,但會增加一些新的堆棧答案。

在Python中有無限的方法可以做到這一點, 這裏有一些例子
正常方式

>>> l= [1,2,"stackoverflow","pytho"] 
>>> l 
[1, 2, 'stackoverflow', 'pytho'] 
>>> tup = tuple(l) 
>>> type(tup) 
>>> tup = tuple(l) 
>>> type(tup) 
<type 'tuple'> 
>>> type(tup) 
<type 'tuple'> 
>>> tup 
(1, 2, 'stackoverflow', 'pytho') 

聰明的辦法

>>>tuple(item for item in l) 
(1, 2, 'stackoverflow', 'pytho') 

記住的元組是不可改變的,用於存儲的東西有價值。例如,密碼,密鑰或哈希存儲在元組或字典中。 如果需要刀,爲什麼要用刀切蘋果。 明智地使用它,也會使你的程序高效。

9

另一個備選方案添加到tuple(l),爲的Python> = 3.5你可以這樣做:

t = *l, # or t = (*l,) 

總之,快,但可能是從可讀性受到影響。

這實質上是在由於單個逗號,的存在而創建的元組文字內部將列表l解包。


P.S:您收到的錯誤是由於您指定名稱的元組某處e.g tuple = (1, 2, 3)名稱tuple即掩蔽。

使用del tuple你應該很好去。

2

這是我在做什麼:

l = [4,5,6] 
tuplex = tuple(l) 
print(tuplex)