I'm putting a new variable in the for statement, but it doesn't work

Asked 2 years ago, Updated 2 years ago, 14 views

ICN_CEIL15 = soup.select_one('table:nth-child(2) > tbody > tr:nth-child(2) > td:nth-child(1) > table > tbody > tr:nth-child(4) > td').text + "'"
ICN_CEIL33 = soup.select_one('table:nth-child(2) > tbody > tr:nth-child(2) > td:nth-child(6) > table > tbody > tr:nth-child(4) > td').text + "'"
ICN_CEIL16 = soup.select_one('table:nth-child(6) > tbody > tr:nth-child(2) > td:nth-child(1) > table > tbody > tr:nth-child(4) > td').text + "'"
ICN_CEIL34 = soup.select_one('table:nth-child(6) > tbody > tr:nth-child(2) > td:nth-child(6) > table > tbody > tr:nth-child(4) > td').text + "'"

ICN_CEILs = [ICN_CEIL15, ICN_CEIL33, ICN_CEIL16, ICN_CEIL34]

for i in ICN_CEILs:
    if i == "'":
        i = "U/S'"

I want to change the variable in ICN_CEILs as a for statement, but it cannot be changed.

If you use print(ICN_CEILs) before for, ["NCD'","",""] comes out like this, and I want to change the two values ("","""U/S") to at the right end, but it doesn't change. I can't see what's wrong.

python

2022-09-20 20:11

1 Answers

i is a variable that is created for a while to contain the list element in the for statement and then disappears. So even if you put a value in i, the value of the original list does not change.

You can do it like this.


for i in range(len(ICN_CEILs)):
    if ICN_CEILs[i] == "'":
        ICN_CEILs[i] = "US'"

By the way, range(len(...) is not pretty and cumbersome, so it's a little simpler if you use enumerate


for i, ele in enumerate(ICN_CEILs):
    if ele == "'":
        ICN_CEILs[i] = "US'"

If you change this back to list compression,

ICN_CEILs = [  "US'" if ele == "'" else ele for ele in ICN_CEILs ]

You can do it like this.


2022-09-20 20:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.