I have a list:
row = ["Title", "url", 33, "title2", "keyword"]
Is there a more pythonic way to unpack these values, for example:
title, url, price, title2, keyword = row[0], row[1], row[2], row[3], row[4]
Something like that?
>>> row = ["Title", "url", 33, "title2", "keyword"] >>> title, url, price, title2, keyword = row
Also for the record, note that your example ends with an IndexError (Python lists are zero-based).
EDIT: The above note was written before the OP example was installed ...
In fact, python automatically unpacks containers when variables are separated by commas. This assigns each element in row variables on the left:
row
title, url, price, title2, keyword = row
After this assignment, title has the value “Heading”, price has a value of 33, etc.
title
price
You can also easily unzip it into a class or namedtuple :
namedtuple
from collections import namedtuple row = ["Title", "url", 33, "title2", "keyword"] Entry = namedtuple("Entry", "title url price title2 keyword") new_entry = Entry(*row) print(new_entry.title) # Title
Also, if you only need the first few variables, in Python 3 you can use:
row = ["Title", "url", 33, "title2", "keyword"] title, url, *_ = row
This is a good way to extract the first few values without using explicit indexes.
Source: https://habr.com/ru/post/1238357/More articles:Android Studio 2.0 (Preview 3b) xml layout not updating in apk? - androidCommunicate and manage the printer device via Bluetooth or USB - printingAndroid WebView keyboard hides input field in fragment in android - androidHow to convert a structure to an array of bytes in C # .net, but the size of the structure, determined only at runtime - arraysEF + AutoFac + async "The current connection status is connecting" - c #"Settings" are not available due to the level of protection - access-modifiersWhy doesn't Github show my installments even though I added my email address? - gitHard Coded Password Detection - javaThere is no cached version of com.android.tools.build:gradle:1.2.3 for offline mode - androidUnverified configuration profile in iOS v.8.3 and later - iosAll Articles