簡體   English   中英

我在這里想念什么? python 中的簡單 for 循環

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

我對 python 很陌生,我正在嘗試一些非常基本的東西,但我似乎沒有得到想要的結果。 最終目標是通過填充不同的詳細信息向端點發送一些 API 調用。 我有一個需要對它們做某事的項目列表,需要對它們應用的操作是 CSV 中包含的不同值,我已經弄清楚如何處理不同的參數並正確填寫 API 調用,現在我需要遍歷 CSV 上的所有行及其相關參數,遍歷項目列表。

所以我有一個文本文件,其中包含如下所示的項目:

1234 5678 3333 5555 等...

還有一個 CSV 文件,其中不同的列代表不同的參數

這是我寫的代碼:

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()

我面臨的問題是它似乎在第一個項目上運行良好,如果我要求打印項目和操作的列表,它會很好地打印它們,但是當運行在調用中發送每行參數的實際操作時對於每個項目,它只在第一個項目上運行並退出。

所以它做了我想要的,但只在文本文件的第一行“1234”上,所有其他的都沒有進入嵌套循環。

我知道我錯過了一些非常基本的東西,我會感謝你的幫助。

謝謝!

csv.DictReader object 是一個迭代器,迭代器只能迭代一次,然后它們就被“消耗”了。

(順便說一下,您的外循環可能可以簡化為

for item in arg_item_list:
    do_stuff_with(item)

如果你也需要索引,你可以做

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

這為您節省了一些 range(len()) 和 [] 鑽頭。)

感謝 Ture Pålsson 的提示,我了解 DictReader object 的“一次性”字符,因此我對此進行了進一步研究,以找到一種可行的方法來盡可能多地重復使用它。 我發現,如果我將其轉換為表格並使用列名和值填充所有行,我就可以像我想要的那樣多次迭代它。 這是最終的代碼:

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()

我希望有人覺得這很有用!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM