سؤال

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