简体   繁体   English

Dataquest:我刚刚学会了如何在 python 中定义一个函数。 现在我想循环运行它。

[英]Dataquest: I've just learned how to define a function in python. Now I want to run it in a loop.

I am a python beginner and I learn using dataquest.我是 Python 初学者,我使用 dataquest 学习。 I want to use a self-defined function in a loop to check every item in a list, whether it is a color movie or not and add the results (True, False) to a list.我想在循环中使用自定义函数来检查列表中的每个项目,它是否是彩色电影,并将结果(真,假)添加到列表中。 Right now the function returns False only, also way to many times.现在该函数仅返回 False,也多次返回。 Any hints what I did wrong?任何提示我做错了什么?

wonder_woman = ['Wonder Woman','Patty Jenkins','Color',141,'Gal Gadot','English','USA',2017]

def is_usa(input_lst):
    if input_lst[6] == "USA":
        return True
    else:
        return False

def index_equals_str(input_lst, index, input_str):
    if input_lst[index] == input_str:
        return True
    else:
        return False

wonder_woman_in_color = index_equals_str(input_str="Color", index=2, input_lst=wonder_woman)

# End of dataquest challenge

# My own try to use the function in a loop and add the results to a list

f = open("movie_metadata.csv", "r")
data = f.read()
rows = data.split("\n")
aufbereitet = []

for row in rows:
    einmalig = row.split(",")
    aufbereitet.append(einmalig)
# print(aufbereitet)

finale_liste = []

for item in aufbereitet:
    test = index_equals_str(input_str="Color", index=2, input_lst=aufbereitet)
    finale_liste.append(test)

print(finale_liste)

Also at pastebin: https://pastebin.com/AESjdirL同样在 pastebin: https : //pastebin.com/AESjdirL

I appreciate your help!我很感激你的帮助!

The problem is in this line问题出在这一行

test = index_equals_str(input_str="Color", index=2, input_lst=aufbereitet)

The input_lst argument should be input_lst=item . input_lst参数应该是input_lst=item Right now you are passing the whole list of lists to your function everytime.现在,您每次都将整个列表列表传递给您的函数。

The .csv file is not provided but I assume the reading is correct and it returns a list like the one you provided in the first line of your code;未提供 .csv 文件,但我认为读数是正确的,它返回一个类似于您在代码第一行中提供的列表; in particular, that you are trying to pack the data in a list of lists (the einmalig variable is a list obtained by the row of the csv file, then you append each einmalig you find in another list, aufbereitet).特别是,您试图将数据打包到列表列表中(einmalig 变量是由 csv 文件的行获得的列表,然后您将在另一个列表 aufbereitet 中找到的每个 einmalig 附加到列表中)。

The problem is not in the function itself but in the parameters you give as inputs: when you do问题不在于函数本身,而在于您作为输入提供的参数:当您这样做时

test = index_equals_str(input_str="Color", index=2, input_lst=aufbereitet)

you should see that the third parameter is not a list corresponding to the single movie data but the whole list of movies.您应该看到第三个参数不是与单个电影数据对应的列表,而是整个电影列表。 This means that the Python interpreter, in the function, does this iteration for every item in aufbereitet (that is, iterates for n times where n is aufbereitet's length):这意味着 Python 解释器在函数中对 aufbereitet 中的每个项目执行此迭代(即迭代 n 次,其中 n 是 aufbereitet 的长度):

if aufbereitet[2] == "Color":
    return True
else:
    return False

It is clear that even if the movie is in color, the comparison between a list (an element of aufbereitet) and a string returns False by default since they are different types.很明显,即使电影是彩色的,列表(aufbereitet 的一个元素)和字符串之间的比较默认返回 False,因为它们是不同的类型。

To correct the issue just change the line要纠正问题,只需更改行

test = index_equals_str(input_str="Color", index=2, input_lst=aufbereitet)

with

test = index_equals_str(input_str="Color", index=2, input_lst=item)

since, when you use the for loop in that way, the variable item changes at each iteration with the elements in aufbereitet.因为,当您以这种方式使用 for 循环时,变量 item 在每次迭代时都会与 aufbereitet 中的元素发生变化。

Notice that if you're learning that's still ok to use functions but you can use an inline version of the algorithm (that's what Python is famous for).请注意,如果您正在学习使用函数仍然可以,但您可以使用算法的内联版本(这就是 Python 的著名之处)。 Using使用

finale_liste = [item[2] == "Color" for item in aufbereitet]

you obtain the list without going to define a function and without using the for loop.您无需定义函数也无需使用 for 循环即可获得列表。 That's called list comprehension.这就是所谓的列表理解。

Another thing you can do to make the code more Pythonic - if you want to use the functions anyway - is to do something like你可以做的另一件事是让代码更 Pythonic - 如果你想使用这些函数 - 是做类似的事情

def index_equals_str(input_lst, index, input_str):
    return input_lst[index] == input_str

that has the same result with less lines.用更少的行获得相同的结果。

Functional programming is sometimes more readable and adaptable for such tasks:对于此类任务,函数式编程有时更具可读性和适应性:

from functools import partial

def index_equals_str(input_lst, index=1, input_str='Null'):
    return input_lst[index] == input_str

input_data = [['Name1', 'Category1', 'Color', 'Language1'],
              ['Name2', 'Category2', 'BW', 'Language2']]

result = list(map(partial(index_equals_str, input_str='Color', index=2), input_data))

# output
# [True, False]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我想在 for 循环结束时打印“否”。 我应该怎么做? - I want to print 'No' at end of the for loop. How should I do? 打印循环时如何执行0? 我一直在尝试在 python 中打印出阶乘。 我需要在输出中打印 0 - How to execute 0 when printing out the loop? I've been trying to print out the factorial in python. I need 0 to be printed in the output 我想在 python 中运行小型 Julia 代码/模块。 我该怎么做? - I want to run small Julia code/modules in python. How should I do that? Python我通过循环将一个列表追加到另一个列表中。 但是我想访问各个输入 - Python I appended a list into another list, via loop. But I want to access the individual inputs 试图应用我学到的知识来构建蛇游戏 python,但它不起作用 - Tried to apply what I've learned to build snake game python but it doesn't work 如何在循环上只运行一次 function? - How do I run a function on a loop just once? 嗨,我正在尝试使用 python 在 Spyder 中构建一个简单的计算器(只是添加)。 如何定义 end 以便删除以前的数字? - Hi, I am trying to build a simple calculator (just adds) in Spyder using python. How do I define end so that it will delete the previous number? Appium + android + python 如何获得我刚刚点击的URL? - Appium + android + python how to get URL that I've just clicked? 我已经安装了可与pip一起运行的GUI应用程序,现在该如何运行它? - I've installed a GUI app to run with pip, now how do i run it? 我已经编写了循环随机数的代码 - 代码有效,但现在我想在每个新数字之间添加字符串 - I've written code where I loop a random - the code works but now I want to add strings between every new number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM