简体   繁体   中英

unpack to int and string in python

Is there a way to unpack to diferent types? this is the case:

# data = [4, "lorem", "ipsum", "dolor", "sit", "amet"]
(parts, *words) = data

data is provided. I never assign this value. I add as example. parts must be an int, all the rest of the list is assigned as list of strings.

The only way that I have found is reassign the variable parts as next:

(parts, *words) = [4, "lorem", "ipsum", "dolor", "sit", "amet"]
parts = int(parts)

but I don't like repeat asignment variable twice in a row. Since python is a language that keeps clean and simple I'm looking a solution.

*edit: Let me know if is a valid practice reassign twice in a row.

In Python's static typing annotations, list s (and all sequences aside from tuple s) are assumed to be of homogeneous type (which may still be a union of multiple types, but it's not a different single type depending on which index you're looking at). Your list is violating that assumption by having index 0 have one type, while the other indices have a different type. Even though Python in general doesn't enforce the "intended" usage of list , type checkers do, and there's no mechanism to work around that shy of manual casts or type conversions, as you're doing here.

Short answer: You're "misusing" list s, and typing won't help you when you do that. So either ignore/disable the type-checker for this code (it'll work just fine after all), or live with a pointless cast.

How about this? It tests each item for type and puts it into the proper list as needed.

data = [4, "lorem", "ipsum", "dolor", "sit", "amet"]
parts = []
words = []
[parts.append(item) if type(item) == int else words.append(item) for item in data]

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