[英]Modifying List elements in a loop
Is it possible to update/modify the list elements/items in a loop. 是否可以在循环中更新/修改列表元素/项目。 Here I have to modify items of
t
在这里我必须修改
t
项
n_wk=[1,2,3,2,3,4,2,3]
t=['a','a','a','a','a','a','a','a']
for i in range(len(n_wk)):
if i==0:
continue
if n_wk[i]<n_wk[i-1]:
if t[i]=='a':
t[i]='b'
elif t[i]=='b':
t[i]='c'
if n_wk[i]>n_wk[i-1]:
t[i]=t[i-1]
I was expecting output t = ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c']
. 我期望输出
t = ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c']
。 But, the output is coming out to be t=['a', 'a', 'a', 'b', 'b', 'b', 'b', 'b']
. 但是,输出结果是
t=['a', 'a', 'a', 'b', 'b', 'b', 'b', 'b']
。 Seems like list t
is not getting updated in the loop. 好像
list t
在循环中没有得到更新。
Can we not update item/elements of the list in a loop? 我们不能循环更新列表中的项目/元素吗?
Your list t
is indeed getting modified: 您的清单
t
确实已被修改:
# t before loop
['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']
# t after loop
['a', 'a', 'a', 'b', 'b', 'b', 'b', 'b']
However, a slight change in your code will give you the result you are looking for: 但是,对代码稍作更改将为您提供所需的结果:
for i in range(len(n_wk)):
if i == 0:
continue
if n_wk[i] < n_wk[i-1]:
if t[i-1] == 'a': #changed from t[i]
t[i] = 'b'
elif t[i-1] == 'b': #changed from t[i]
t[i] = 'c'
if n_wk[i] > n_wk[i-1]:
t[i] = t[i-1]
print(t)
# ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c']
Here's a method that does not loop using indexes and does not require t
to be initialized with 'a'
s to begin with: 这是一种不会循环使用索引并且不需要以
'a'
开头的t
开头的方法:
n_wk = [1,2,3,2,3,4,2,3]
t = []
n_prev = 0
t_prev = 'a'
for n in n_wk:
t_new = t_prev
if n < n_prev:
if t_prev == 'a':
t_new = 'b'
elif t_prev == 'b':
t_new = 'c'
t.append(t_new)
n_prev = n
t_prev = t_new
print(t)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.