简体   繁体   中英

Unpacking list with tuple in python

let's say, we have this list with tuple

general = [(a, b, c)]

and I want to unpack it.

Why doesn't this work:

[value, value1, value2] = general

But this does?

[temp] = general
value, value1, value2 = temp

Shouldn't it be the same?

Are there other alternative, shorter ways to do this?

Unpacking is roughly the inverse of packing. When packing data like this:

general = [(a, b, c)]

It can be unpacked by swapping the assignment like this:

[(a, b, c)] = general

Using a flatter or deeper pattern, such as [a, b, c] = general or [[(a, b, c)]] = general , does not match the data and thus fails to unpack. An intermediate assignment, such as [temp] = general , can be used to reduce/increase the depth but is not needed when the proper pattern is used directly.

general is a list, so what you're trying to do here [value, value1, value2] = general is assignate your value to the ones in the list, but here your list has only one element which is your tuple

that's why when you do [temp] = general you assignate temp to the unique value of general.

so what you could do is [value, value1, value2] = general[0]

since general is a list containing the tuple, you should unpack the list containing the tuple first, and then unpacking the tuple to get the values

general = [(a, b, c)]
value1, value2, value3 = general[0]

Python is working correctly. You are trying to save objects within a tuple within an array to multiple objects. Please try to unpack it once first.

This will work fine:

value, value1, value2 = [(a, b, c)][0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM