質問

Say I have the following code:

from urlparse import urlparse
parsed_url = urlparse(url)
scheme, netloc, path = parsed_url[0], parsed_url[1], parsed_url[2]

Is there a more elegant or short way of assigning those three variables? It looks a bit messy to write parsed_url three times (I am expecting something other than renaming parsed_url to something shorter).

役に立ちましたか?

解決

You can cut the tuple in half:

scheme, netloc, path = parsed_url[:3]

Or, to make it explicit that there are six values and you're ignoring three of them, you could assign to a dummy variable named _:

scheme, netloc, path, _, _, _ = parsed_url

他のヒント

parsed_url[:3] will create a subtuple consisting of exactly the wanted parts.

So

scheme, netloc, path = parsed_url[:3]

will do what you need.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top