简体   繁体   English

我在这里想念什么? python 中的简单 for 循环

[英]What am I missing here? Simple for loop in python

I'm quite new with python and I'm trying something very basic but I don't seem to get the desired result.我对 python 很陌生,我正在尝试一些非常基本的东西,但我似乎没有得到想要的结果。 The final goal is to send a few API calls to an endpoint by populating different details.最终目标是通过填充不同的详细信息向端点发送一些 API 调用。 I have a list of items I need to do something with them, the actions that need to be applied to them are different values contained in a CSV, I've figured out how to handle the different parameters and fill in in the API call properly, now I need to iterate all rows on the CSV, with their relevant parameters, over a list of items.我有一个需要对它们做某事的项目列表,需要对它们应用的操作是 CSV 中包含的不同值,我已经弄清楚如何处理不同的参数并正确填写 API 调用,现在我需要遍历 CSV 上的所有行及其相关参数,遍历项目列表。

So I have a text file with items that looks like this:所以我有一个文本文件,其中包含如下所示的项目:

1234 5678 3333 5555 etc... 1234 5678 3333 5555 等...

And a CSV file with different columns that represent different parameters还有一个 CSV 文件,其中不同的列代表不同的参数

Here's the code I wrote:这是我写的代码:

items_file = 'itemlist.txt'
action_file = 'actions.csv'

file_handle = open(action_file, "r", encoding="utf8")
csv_reader = DictReader(file_handle)

with open(items_file, "r") as myfile:
    item_list = myfile.read().splitlines()


def actions(arg_item_list):
    for item in range(len(arg_item_list)):
        for row in csv_reader:
            print('do something with ' arg_item_list[item]) 
            blah 
            blah...
            

actions(item_list)

file_handle.close()

The problem I'm facing is that it seems to run fine on the first item, and if I ask to print the list of items and actions it will print them fine, but when running the actual actions of sending each row params on a call for each item, it only runs on the first one and exits.我面临的问题是它似乎在第一个项目上运行良好,如果我要求打印项目和操作的列表,它会很好地打印它们,但是当运行在调用中发送每行参数的实际操作时对于每个项目,它只在第一个项目上运行并退出。

So it does what I want but only on "1234" which is the first line of the text file, all the others are not getting into the nested loop.所以它做了我想要的,但只在文本文件的第一行“1234”上,所有其他的都没有进入嵌套循环。

I know I'm missing something very basic, and I'll appreciate your kind help.我知道我错过了一些非常基本的东西,我会感谢你的帮助。

Thanks!谢谢!

The csv.DictReader object is an iterator, and iterators can only be iterated over once, then they're "spent". csv.DictReader object 是一个迭代器,迭代器只能迭代一次,然后它们就被“消耗”了。

(And by the way, your outer loop can probably be simplified to (顺便说一下,您的外循环可能可以简化为

for item in arg_item_list:
    do_stuff_with(item)

if you need the index too, you can do如果你也需要索引,你可以做

for index, item in enumerate(item_list):
    print("item number", index, "is", item)

This saves you some range(len()) and [] drill.)这为您节省了一些 range(len()) 和 [] 钻头。)

Thanks Ture Pålsson for the hints, I understood the "disposable" character of the DictReader object, so I've researched this further to find a viable way to be able to reuse it as much as I can.感谢 Ture Pålsson 的提示,我了解 DictReader object 的“一次性”字符,因此我对此进行了进一步研究,以找到一种可行的方法来尽可能多地重复使用它。 I've found that if I convert this to a table and populate all rows with columns names and values I'm able to iterate over it similarly to what I did just as many times as I want.我发现,如果我将其转换为表格并使用列名和值填充所有行,我就可以像我想要的那样多次迭代它。 Here's the final code:这是最终的代码:

import csv
from csv import DictReader
from typing import List, Dict


items_file = 'itemlist.txt'
action_file = 'actions.csv'

file_handle = open(action_file, "r", encoding="utf8")
csv_reader = list(DictReader(file_handle))
table: List[Dict[str, str]] = [] #in my case, all values were strings, but you could use this also to convert it to other types, e.g. List[Dict[str, float] = [].

with open(items_file, "r") as myfile:
    item_list = myfile.read().splitlines()


for row in csv_reader:
    str_row: Dict[str, str] = {} 
    for column in row:
        str_row[column] = str(row[column])
    table.append(str_row)


def actions(arg_item_list):
    for item in arg_item_list:
        for row in table:
            print('apply actions from columns data on rows by their name e.g. ', row['action_column_1'], row['any_other_column_name']
            print('and apply them on ' arg_item_list[item]) 
            

actions(item_list)

file_handle.close()

I hope someone finds this useful!我希望有人觉得这很有用!

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

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