如何更改for循环以将项目存储在列表中以进行写入

时间:2013-10-21 16:08:59

标签: python csv

我有这个代码,根据我的脚本在.csv中的结果(只重复打印一个UserID)我假设我的变量被覆盖并重新分配每次迭代。

# User_alias is a raw input (of multiple items)

    print user_alias
        for user in user_alias:
            for row in Dict_list:    
                if user in row.values():
                    print row

        for user in user_alias:
            for row in Dict_list:
                if row.has_key('_akq6p') and row.has_key('_cn6ca'):
                    if user == row['_akq6p'] or user == row['_chk2m']:


#EDIT:
                    UserID = row['_cn6ca']
                    UserIDs=[]
                    UserIDs.append(row['_cn6ca'])
                    print UserIDs

以下是输入/输出示例:

Raw input:
Adue Sal
Arthur Bel
Abby Sue

['Adue Sal', 'Art Baraan', 'Abbey Shi']
{'_akq6p': 'adkul', '_dcgjs': 'adkul', '_chk2m': 'Adue Sal', '_cn6ca': '1200df00'}
{'_akq6p': 'artb', '_dcgjs': 'artb', '_chk2m': 'Arthur Bel', '_cn6ca': '00123ffj8'}
{'_akq6p': 'abbys', '_dcgjs': 'abbys', '_chk2m': 'Abby Sue', '_cn6ca': '125gh789'}
['1200df00']
['00123ffj8']
['125gh789']
logout

[Process completed]

我需要将它们写入.csv,所以我需要存储每个ID,但这段代码似乎只存储了查找的最后一个ID。我如何存储所有这些ID以供以后写作?

1 个答案:

答案 0 :(得分:0)

以下是我的动态:http://codecube.io/TlFgaY

您需要在循环外创建列表,然后添加到它。

print user_alias
for user in user_alias:
    for row in Dict_list:    
        if user in row.values():
            print row

UserIDs = [] # This is the change.
for user in user_alias:
    for row in Dict_list:
        if row.has_key('_akq6p') and row.has_key('_cn6ca'):
            if user == row['_akq6p'] or user == row['_chk2m']:
                UserID = row['_cn6ca']
                print UserID
                UserIDs.append(UserID)

print UserIDs