在Python中使用一个元素创建一个元组
It's not simple to create a tuple with one element, if we try to create a tuple with parenthesis or without parenthesis, tuple will not be created.
創(chuàng)建具有一個(gè)元素的元組并不簡單,如果我們嘗試創(chuàng)建帶有括號或不帶括號的元組,則不會(huì)創(chuàng)建元組。
Consider the below example,
考慮下面的示例,
tuple1 = ("Hello") print("type of tuple1: ", type(tuple1))tuple2 = "Hello" print("type of tuple2: ", type(tuple2))Output
輸出量
type of tuple1: <class 'str'> type of tuple2: <class 'str'>See the output, the type of tuple1 and tuple2 is str.
看到輸出, tuple1和tuple2的類型為str 。
Then, how to create a tuple with one element?
然后, 如何用一個(gè)元素創(chuàng)建一個(gè)元組?
It's little tricky to create a tuple with one element, we need to use a trailing comma after the element that represents that it is a tuple.
創(chuàng)建具有一個(gè)元素的元組有點(diǎn)麻煩, 我們需要在表示它是元組的元素后使用尾隨逗號 。
Consider the below example,
考慮下面的示例,
tuple1 = ("Hello",) print("type of tuple1: ", type(tuple1))tuple2 = "Hello", print("type of tuple2: ", type(tuple2))tuple3 = (100,) print("type of tuple3: ", type(tuple3))tuple4 = 100, print("type of tuple4: ", type(tuple4))Output
輸出量
type of tuple1: <class 'tuple'> type of tuple2: <class 'tuple'> type of tuple3: <class 'tuple'> type of tuple4: <class 'tuple'>Now, see the output, the type of variables is tuple. Hence, we can create one element tuple by using a trailing comma after the element and it works with and without parenthesis.
現(xiàn)在,查看輸出,變量的類型為tuple 。 因此,我們可以通過在元素后使用尾部逗號來創(chuàng)建一個(gè)元素元組,并且該元素可以在帶或不帶括號的情況下使用。
翻譯自: https://www.includehelp.com/python/creating-a-tuple-with-one-element.aspx
總結(jié)
以上是生活随笔為你收集整理的在Python中使用一个元素创建一个元组的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ruby 三目运算符_Ruby运算符
- 下一篇: Java FilterInputStre