Skip to main content
 首页 » 编程设计

python之无法遍历字符串列表

2025年05月04日49lyj

我在遍历列表以将项目添加到字典列表时遇到问题。我相信我的问题出在 list_to_dictionary 函数中。 “for muns in mun”返回列表中的一项“Mun”。它只遍历列表一次,因为它说列表中的唯一项目是“Mun”。我需要为每个事件创建一个字典。不确定是什么问题,谢谢。

#iterates though lists and puts value at location "count" 
#into a dictionary and loops until there are no more events 
def list_to_dictionary(): 
    count = 0 
    for muns in mun: 
        print muns 
        event = {'Agency ': agency[count], 'Time ': time[count], 'Units ': units[count], 'Description ': description[count], 'Street ': street[count], 'Cross Streets ': crossStreets[count], 'Municipality ': mun[count]} 
        count += 1 
        return event 
 
create_list(allTable) 

请您参考如下方法:

return event 

在你的循环中,所以循环在第一次迭代时停止。

您可能想将事件添加到字典列表并在循环之后返回列表

def list_to_dictionary(): 
    count = 0 
    events = [] 
    for muns in mun: 
        print muns 
        event = {'Agency ': agency[count], 'Time ': time[count], 'Units ': units[count], 'Description ': description[count], 'Street ': street[count], 'Cross Streets ': crossStreets[count], 'Municipality ': mun[count]} 
        events.append(event) 
        count += 1 
    return events