简体   繁体   English

Python-通过enumerate()迭代和替换列表索引

[英]Python - Iterating and Replacing List Index via enumerate()

I have a python script that imports a CSV file and based on the file imported, I have a list of the indexes of the file. 我有一个导入CSV文件的python脚本,并基于导入的文件,列出了该文件的索引。

I am trying to match the indexes in FILESTRUCT to the CSV file and then replace the data in the column with new generated data. 我正在尝试将FILESTRUCT中的索引匹配到CSV文件,然后用新生成的数据替换列中的数据。 Here is a code snip-it: 这是一个代码片段:

This is just a parsed CSV file returned from my fileParser method: 这只是从我的fileParser方法返回的已解析的CSV文件:

PARSED = fileParser() 

This is a list of CSV column positions: 这是CSV列位置的列表:

FILESTRUCT = [6,7,8,9,47]

This is the script that is in question: 这是有问题的脚本:

def deID(PARSED, FILESTRUCT):
    for item in PARSED:
            for idx, lis in enumerate(item):                        
                    if idx == FILESTRUCT[0]:
                           lis = dataGen.firstName()

                    elif idx == FILESTRUCT[1]:
                            lis = dataGen.lastName()

                    elif idx == FILESTRUCT[2]:
                            lis = dataGen.email()

                    elif idx == FILESTRUCT[3]:
                            lis = dataGen.empid()

                    elif idx == FILESTRUCT[4]:
                            lis = dataGen.ssnGen()

                    else:
                            continue

    return(PARSED)

I have verified that it is correctly matching the indices (idx) with the integers in FILESTRUCT by adding a print statement at the end of each if statement. 我已经通过在每个if语句的末尾添加一条print语句,验证它正确地将索引(idx)与FILESTRUCT中的整数匹配。 That works perfectly. 那很好。

The problem is that when I return(PARSED) it is not returning it with the new generated values, it is instead, returning the original PARSED input values. 问题是当我返回(PARSED)时,它没有使用新生成的值返回它,而是返回了原始的PARSED输入值。 I assume that I am probably messing something up with how I use the enumerate method in my second loop, but I do not understand the enumerate method well enough to really know what I am messing up here. 我以为我可能在第二个循环中弄乱了如何使用枚举方法,但是我对枚举方法的理解不够充分,以至于无法真正知道自己在这里搞砸了什么。

You can use 您可以使用

item[idx] = dataGen.firstName()

to modify the underlying item . 修改基础item The reason here is that enumerate() returns (id, value) tuples rather than references to the iterable that you passed. 这里的原因是enumerate()返回(id, value)元组,而不是对您传递的可迭代对象的引用。

Given your example above you may not even need enumerate , because you're not parsing the lis at all. 在上面的示例中,您甚至不需要enumerate ,因为您根本不需要解析lis So you could also just do 所以你也可以做

for i in range(len(item)):
    # your if .. elif statements go here ...
    item[i] = dataGen.firstName()

On a side-note, the elif statements in your code will become unwieldy once you start adding more conditions and columns. 附带一提,一旦开始添加更多条件和列,代码中的elif语句将变得笨拙。 Maybe consider making FILESTRUCT a dictionary like: 也许考虑将FILESTRUCT做成字典,例如:

FILESTRUCT = {
    6: dataGen.firstName,
    7: dataGen.lastName,
    ....
    }
...
for idx in range(len(item)):
    if idx in FILESTRUCT.keys():
        item[idx] = FILESTRUCT[idx]()

So PARSED is an iterable, and item is an element of it and is also an iterable, and you want to make changes to PARSED by changing elements of item . 因此, PARSED是可迭代的, item是它的元素,也是可迭代的,您想通过更改item元素来对PARSED进行更改。

So let's do a test. 因此,让我们进行测试。

a = [1, 2, 3]
print 'Before:'
print a

for i, e in enumerate(a):
    e += 10

print 'After:'
print a

for e in a:
    e += 10

print 'Again:'
print a

a[0] += 10

print 'Finally:'
print a

The results are: 结果是:

Before:
[1, 2, 3]
After:
[1, 2, 3]
Again:
[1, 2, 3]
Finally:
[11, 2, 3]

And we see, a is not changed by changing the enumerated elements. 我们看到, a不会通过更改枚举元素来更改。

You aren't returning a changed variable. 您不会返回已更改的变量。 You don't ever change the variable FILESTRUCT. 您永远不会更改变量FILESTRUCT。 Rather make another variable, make it as you loop through FILESTRUCT and then return your new FILE. 而是创建另一个变量,使其在遍历FILESTRUCT时返回它,然后返回新的FILE。

You can't change the values in a loop like that, Kind of like expecting this to return all x's: 您不能在这样的循环中更改值,有点像期望它返回所有x:

demo_data = "A string with some words"
for letter in demo_data:
    letter = "x"
return demo_data

It won't, it will return: "A string with some words" 不会,它将返回: "A string with some words"

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

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