0

我从下面的代码得到的这个结果是错误的:

[
'199|4|11|GDSPV', 
'199|4|11|GDSPV|199|16|82|GDSPV', 
'199|4|11|GDSPV|199|16|82|GDSPV|205|16|82|GDSPV'
]

我希望结果与fr列表相同,但将 email 替换为字典d的值。我完全不知道为什么这不能按预期工作?

fr = [
'7@comp1.COM|4|11|GDSPV',
'7@comp1.COM|16|82|GDSPV',
'13@comp1.COM|16|82|GDSPV'
]

d= {
'7@comp1.COM': '199',
'8@comp4.COM': '200',
'13@comp1.COM': '205'
}


col_list=[]
line_list=[]

for line in fr:
    columns = line.split("|")
    for col in columns:
        if col==columns[0]:
            col_list.append(d[col])
            continue
        col_list.append(col)
        #i = i + 1
    line_list.append("|".join(col_list))
print line_list
4

4 回答 4

1

当您开始处理每一行时,您需要重置 col_list。即在col_list=[]之前拨打电话for col in columns:

于 2012-11-27T04:22:42.747 回答
1

试试这个:

line_list=[]
for line in fr:
    cols = line.split('|')
    key = cols[0]
    cols[0]=d[key]
    line_list.append('|'.join(cols))

print line_list
于 2012-11-27T04:24:03.163 回答
1

你几乎在那里:

# col_list=[] you don't need this
line_list=[]

for line in fr:
    columns = line.split("|")
    looking_for = columns[0] # this is what we need to search
    if looking_for in d:
        # by default, iterating over a dictionary will return keys
        new_line = d[looking_for]+'|'+'|'.join(columns[1:])
        line_list.append(new_line)
print line_list
于 2012-11-27T04:38:09.360 回答
0

检查这个......在sample.py

fr = [
'7@comp1.COM|4|11|GDSPV',
'7@comp1.COM|16|82|GDSPV',
'13@comp1.COM|16|82|GDSPV'
]

d= {
'7@comp1.COM': '199',
'8@comp4.COM': '200',
'13@comp1.COM': '205'
}

col_list=[]
line_list=[]

for line in fr:
    columns = line.split("|")
    if d.has_key(columns[0]):
        col_list.append(d[columns[0]])
    else:
        col_list.append(columns[0])
    col_list.extend(columns[1:])
    line_list.append("|".join(col_list))

print line_list

输出

D:\>python sample.py
['199|4|11|GDSPV', '199|4|11|GDSPV|199|16|82|GDSPV', '199|4|11|GDSPV|199|16|82|G
DSPV|205|16|82|GDSPV']
于 2012-11-27T04:37:07.247 回答