数据类型3.2将列表中的元素重新赋值

将列表[3,7,0,5,1,8]中大于5元素置为0,小于5的元素置为1

Tip:使用enumerate函数,enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中

list1 = [3,7,0,5,1,8]
for i,j in enumerate(list1):
    if j > 5:
        list1[i] = 0
    elif j < 5:
        list1[i] = 1
print(list1)

结果输出:

[1, 0, 1, 5, 1, 0]

Process finished with exit code 0

猜你喜欢

转载自www.cnblogs.com/hrv5/p/12004788.html