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