Python, split tuple items to single stuff

∥☆過路亽.° 提交于 2019-11-30 07:54:50

问题


I have tuple in Python that looks like this:

tuple = ('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', 'Facebook')

and I wanna split it out so I could get every item from tuple independent so I could do something like this:

domain = "sparkbrowser.com"
level = 0
url = "http://facebook.com/sparkbrowser"
text = "Facebook"

or something similar to that, My need is to have every item separated. I tried with .split(",") on tuple but I've gotten error which says that tuple doesn't have split option

Any help or advice is welcome


回答1:


Python can unpack sequences naturally.

domain, level, url, text = ('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', 'Facebook')



回答2:


Best not to use tuple as a variable name.

You might use split(',') if you had a string like 'sparkbrowser.com,0,http://facebook.com/sparkbrowser,Facebook', that you needed to convert to a list. However you already have a tuple, so there is no need here.

If you know you have exactly the right number of components, you can unpack it directly

the_tuple = ('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', 'Facebook')
domain, level, url, text = the_tuple

Python3 has powerful unpacking syntax. To get just the domain and the text you could use

domain, *rest, text = the_tuple

rest will contain [0, 'http://facebook.com/sparkbrowser']




回答3:


>>> domain, level, url, text = ('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', 'Facebook')
>>> domain
'sparkbrowser.com'
>>> level
0
>>> url
'http://facebook.com/sparkbrowser'
>>> text
'Facebook'



回答4:


An alternative for this, is to use collections.namedtuple. It makes accessing the elements of tuples easier.

Demo:

>>> from collections import namedtuple
>>> Website = namedtuple('Website', 'domain level url text')
>>> site1 = Website('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', 'Facebook')
>>> site2 = Website('foo.com', 4, 'http://bar.com/sparkbrowser', 'Bar')
>>> site1
Website(domain='sparkbrowser.com', level=0, url='http://facebook.com/sparkbrowser', text='Facebook')
>>> site2
Website(domain='foo.com', level=4, url='http://bar.com/sparkbrowser', text='Bar')
>>> site1.domain
'sparkbrowser.com'
>>> site1.url
'http://facebook.com/sparkbrowser'
>>> site2.level
4


来源:https://stackoverflow.com/questions/18372952/python-split-tuple-items-to-single-stuff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!