简体   繁体   English

如何在python中用不同的参数多次调用一个function?

[英]How to call a single function multiple times with different parameters in python?

list = ["a","b","c"]
def type(count):
    res2=list[count]
    for row1 in csv_reader1:   # Values imported from CSV
        res2=list[count]
        print(res2)
        res1 = str(row1)[1:-1]
        res3 = str(res1)[1:-1]
        print(res3)
type(0)
type(1)
type(2)

I want to call this type function, type(0) is being called, but then it exits and type(1) and type(2) are not being called.我想调用此类型 function,正在调用 type(0),但随后它退出并且没有调用 type(1) 和 type(2)。 I've even tried with for loop我什至尝试过 for 循环

for i in range(0,2):
    type(i)
    i=i+1

Even this For doesn't work, it just calls type(0) and exits.即使这个 For 也不起作用,它只是调用 type(0) 并退出。

I've defined a list and I'm trying to iterate list for each value of imported from CSV. Kind of for-each in powershell - for-each list( print res2( = list) and print(each value in CSV) ) - This is what I'm trying to achieve.我已经定义了一个列表,我正在尝试为从 CSV 导入的每个值迭代列表。powershell 中的 for-each 类型 - for-each 列表(打印 res2(= 列表)和打印(CSV 中的每个值)) - 这就是我想要实现的目标。 I'm new to Python. Any help would be greatly appreciated.我是 Python 的新手。非常感谢任何帮助。 Thanks in advance.提前致谢。

I assume you are creating a CSV reader something like this:我假设您正在创建一个 CSV 阅读器,如下所示:

import csv
with open("myfile.csv") as f:
    csvreader1 = csv.reader(f)

This reader object can only be read once and is then used up.这个读卡器object只能读一次就用完了。 That's why your function doesn't do anything the 2nd and 3rd times.这就是为什么您的 function 第二次和第三次没有做任何事情的原因。 To be able to reuse the content, use list to read the whole file into memory.为了能够重用内容,使用list将整个文件读入 memory。

with open("myfile.csv") as f:
    csv_content = list(csv.reader(f))

Alternatively, rewrite your function so that it reads the CSV each time.或者,重写您的 function 以便它每次都读取 CSV。

letters = ["a","b","c"]
def print_data(i, filename):
    print(letters[i])
    with open(filename) as f:
        for row in csv.reader(f):   # Values imported from CSV
            print(str(row)[2:-2])

print_data(0, "myfile.csv")
list = ["a","b","c"]
file = open("C:/Users/data.csv") 
csv_reader = csv. reader(file)
def type(count):
    res2=list[count]
    
    for row1 in csv_reader:   # Values imported from CSV
        res2=list[count]
        print(res2)
        res1 = str(row1)[1:-1]
        res3 = str(res1)[1:-1]
        print(res3)

for i in range(0,2):
    type(i)

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

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