开发者

Are there more ways to define a tuple with only one item?

I know this is one way, by placing a comma:

>>> empty = ()
>>> singleton = 'hello',    # <-- note trailing comma
>>&g开发者_开发问答t; len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)

Source: http://docs.python.org/tutorial/datastructures.html

Are there more ways to define a tuple with only 1 item?


>>> tuple(['hello'])
('hello',)

But the built-in syntax is there for a reason.


Even though you can define a tuple as 'hello', I think it would be easy for someone to possibly miss the trailing comma if they were reading your code. I definitely prefer ('hello',) from a readability stand-point.


singleton = ('hello',)

This is more clear I guess, and @jleedev even more clear. But I like the method you used the best:

singleton = 'hello',


Another one is

>>> (1, 2)[0:1]
(1,)

A very obfuscated way, but it is an alternative...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜