Python字符串神奇地轉換為元組。為什么?

[英]Python string converts magically to tuple. Why?


I've got a dict in which I load some info, among others a name which is a plain string. But somehow, when I assign it to a key in the dict it gets converted to a tuple, and I have no idea why.

我有一個dict,其中我加載了一些信息,其中一個名稱是一個普通的字符串。但不知何故,當我將它分配給dict中的一個鍵時,它會轉換為一個元組,我不知道為什么。

Here's some of my code:

這是我的一些代碼:

sentTo = str(sentTo)
print type(sentTo), sentTo
ticketJson['sentTo'] = sentTo,
print type(ticketJson['sentTo']), ticketJson['sentTo']

which outputs the following on my terminal:

在我的終端輸出以下內容:

<type 'str'> Pete Chasin
<type 'tuple'> ('Pete Chasin',)

Why does assigning it to a dict convert it to a tuple?

為什么將它分配給dict會將其轉換為元組?

2 个解决方案

#1


14  

You told Python to create a tuple containing a string:

你告訴Python創建一個包含字符串的元組:

ticketJson['sentTo'] = sentTo,
#                            ^

It is the comma that defines a tuple. Parentheses are only needed to disambiguate a tuple from other uses of a comma, such as in a function call.

它是定義元組的逗號。僅需要括號來消除元組與其他逗號使用的歧義,例如在函數調用中。

From the Parenthesized forms section:

從括號表單部分:

Note that tuples are not formed by the parentheses, but rather by use of the comma operator. The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.

請注意,元組不是由括號組成,而是使用逗號運算符。唯一的例外是空元組,需要括號 - 在表達式中允許不帶括號的“無”會導致含糊不清並允許常見錯別字傳遞未被捕獲。

and from Expression lists:

從表達式列表:

An expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.

包含至少一個逗號的表達式列表產生一個元組。元組的長度是列表中表達式的數量。表達式從左到右進行評估。

#2


2  

ticketJson['sentTo'] = sentTo, is single element tuple

ticketJson ['sentTo'] = sentTo,是單元素元組


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/09/10/729a2da532267609684787cb9c574804.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com