Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

list - Unpacking values from a tuple onto two variables inside a for loop in Python 3.8.0

I'm trying to unpack strings from a tuple (or could be a list) onto two variables within a for loop. Those variables get replaced with the next set of values every iteration; my problem lies in that the same syntax works with a simple test outside the for loop. My code is as follows:

a,b = tuple("First Name-Second Name".split("-")) # here a tuple unpacks directly and it works
print (a,b)
a,b = "Third Name - Fourth Name".split("-") # here a list unpacks directly and it works
print (a,b)
# this one worked, for some reason, which further confuses me

for row in sheet2: # rows in an excel sheet
    names = row[0].value # the string value of each row
    name1,name2 = tuple(names.split("-")) # splitting the string into two words which are ALL separated by an '-' and trying to store them into two variables
    print (name1,name2) # printing the result (not intended task, only checking if script works up to the point)

The result is this:

First Name Second Name
Third Name   Fourth Name
Traceback (most recent call last):
File "name of my file that I'm censoring for privacy reasons", line 40, in <module>
name1,name2 = tuple(names.split("-")) # splitting the string into two words which are ALL separated by an '-' and trying to store them into two variables
ValueError: not enough values to unpack (expected 2, got 1)

If you run this code you'll notice that the for loop fails and the program stops, and yet the code outside that block does work, even though it uses the exact same syntax and variable inputs. I've already looked up tuple and list unpacking, tried everything that is supposed to work, yet nothing works inside that for loop. I know I could just store my string in a variable then calling the variable's values individually to store in name1 and name2. But I also want to understand what's going wrong and learn from this.

I have found two similar questions:

  1. behaviour of tuple unpacking in a for loop compared to inline
  2. Unpacking a tuple in for loop

Neither of which answered my question. Or maybe, the answers are too difficult for me to understand. If it's the same question, can someone explain this in simpler terms please?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...