Python csv reader for row in reader - what does the the throwaway underscore represent in this code?

元气小坏坏 提交于 2020-04-18 05:50:15

问题


I'm reading data from a csv file. I get that 'row' is the variable that represents the loop I am going through, but what is the "_" that is being thrown away here?

for row in csv_reader:
  _, Student.objects.get_or_create(
      first_name=row[0],
      last_name=row[1],
      email=row[2],
      organisation=row[3],
      enrolled=row[4],
      last_booking=row[5],
      credits_total=row[6],
      credits_balance=row[7],
      )

For example, this code also works:

for row in csv_reader:
  Student.objects.get_or_create(
    first_name=row[0],
    last_name=row[1],
    email=row[2],
    organisation=row[3],
    enrolled=row[4],
    last_booking=row[5],
    credits_total=row[6],
    credits_balance=row[7],
    )

So I could also ask, why is the "_," even there in the first place?

I found the idea in another question's answer but the purpose of the underscore was not explained.

UPDATE NOTE

So it seems that I made a slight error when copying the original code from another post. The original code was:

  for row in csv_reader:
    _, result = Student.objects.get_or_create(...

which makes more sense now that I see this answer. The code is meant to be unpacking the RESULT of the get_or_create and throwing away one value of the tuple. I mistakenly did not copy the result variable as part of my code.


回答1:


I have a feeling there may be a slight syntax error here.

get_or_create() returns a tuple; the object and a boolean (true if the object has been created).

An underscore is sometimes used for one of the elements in that tuple (the bool for example)

instance, _ = MyObject.objects.get_or_create()

So here _, Student.objects.get_or_create is actually valid python I just think maybe you're missing the second variable to unpack the returned tuple. If you print the type print(type(_)), it'll return "tuple" and if you print(_) you should see a tuple containing the object and the boolean.

Adding the , after _ makes _ a tuple which is why it's not giving you an error, if you remove the , it'll throw an error and if you do _,instance it'll throw an error as you'd need the = Student.... if you're unpacking the whole tuple.




回答2:


_ has to have been defined earlier in your code-block if that code doesn't produce a syntax-error. It could be defined outside of the loop all together, and could be a "scope"-issue with the variable.

To give you a weird example for how it can be used though, we can use it inside of another loop and just "catch" the variable and do nothing with it:

d = {1:"A", 2:"B", 3:"C"}
for _, value in d.items():
    print(value)

Output:

A
B
C


来源:https://stackoverflow.com/questions/61229166/python-csv-reader-for-row-in-reader-what-does-the-the-throwaway-underscore-rep

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!