简体   繁体   English

Python 3.6.9 - 列表 - 在 for 循环中就地修改

[英]Python 3.6.9 - Lists - In-place modification in a for loop

Background :背景

I have a list of names and email addresses stored in a Python list.我有一个名称列表和 email 地址存储在 Python 列表中。

user_data_list = [['Adam', 'adam@abc.com'],
                  ['Alice', 'alice@stu.edu'],
                  ['Eve', 'eve@abc.com'],
                  ['Bob', 'bob@abc.com']]

I have two lists containing the old and the updated email addresses, old_domain_email_list and new_domain_email_list , respectively.我有两个列表,分别包含旧的和更新的 email 地址old_domain_email_listnew_domain_email_list The contents of the lists are:列表的内容是:

old_domain_email_list = ['adam@abc.com', 'eve@abc.com', 'bob@abc.com']
new_domain_email_list = ['adam@xyz.com', 'eve@xyz.com', 'bob@xyz.com']

I intend to update the email addresses to now contain xyz.com instead of abc.com .我打算将 email 地址更新为现在包含xyz.com而不是abc.com The below lines of code iterates through the user_data_list and updates the matched entries in the list.下面的代码行遍历user_data_list并更新列表中的匹配条目。


for user in user_data_list:
    for old_domain_email, new_domain_email in zip(old_domain_email_list, new_domain_email_list):
        if user[1] == old_domain_email:
            user[1] = new_domain_email

The changed name and email address pairs are then written to a CSV file.然后将更改后的nameemail address对写入 CSV 文件。

with open(report_file_location, 'w+') as output_file:
        writer = csv.writer(output_file)
        writer.writerows(user_data_list)
        output_file.close()

Query :查询

Are the user details in the user_data_list updated by the line user[1] = ' ' + new_domain_email happening in-place ? user_data_list中的用户详细信息是否由行user[1] = ' ' + new_domain_email发生更新? The code doesn't explicitly tries to modify the user_data_list , but still, the writer.writerows(user_data_list) method correctly creates the new file with the updated domain names.该代码没有显式尝试修改user_data_list ,但是writer.writerows(user_data_list)方法仍然正确地创建了具有更新域名的新文件。

Python version used: 3.6.9 Python 使用的版本:3.6.9

I hope I am able to make the question clear.我希望我能把问题说清楚。

Yes, the modification is happening in place.是的,修改正在进行中。 user[i] =... invokes user 's __setitem__ method which does not change the object to which the user reference points. user[i] =...调用user__setitem__方法,该方法不会更改user参考指向的 object。

Yes, it is.是的。 You can simplify the email address replacement using list comprehension.您可以使用列表解析来简化 email 地址替换。

[[i[0], i[1].split('@')[0]+'@xyz.com'] for i in user_data_list]

result:结果:

[['Adam', 'adam@xyz.com'], ['Alice', 'alice@xyz.com'], ['Eve', 'eve@xyz.com'], ['Bob', 'bob@xyz.com']]

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

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