如何替换列表中的值 [英] How to replace a value in a list

查看:373
本文介绍了如何替换列表中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序要求用户输入5个唯一号码,如果该号码已在列表中,则要求输入一个新号码.输入5个唯一编号后,显示列表

the program asks user to enter 5 unique number, if the number is already in the list, ask for a new number. after 5 unique numbers have been entered, display the list

numbers = ['1','2','3','4','5']
count = 0
index = 0
while count <6:
    user = raw_input ("Enter a number: ")
    if user in numbers:
        print "not unique"
    if user not in numbers:
        print "unique"
        count += 1
        numbers = numbers.replace(index,user)
        index +=1
    print numbers

程序进入替换方法时,会引发属性错误

when the program gets to the replace method, it raise an attribute error

推荐答案

您可以使用:

numbers[index] = user

列表没有replace()方法.字符串确实具有替换方法.

A list doesn't have a replace() method. A string does have a replace method however.

如果希望在列表末尾添加数字,则可以使用append():

If you wish to append a number to the end of a list, you can use append():

numbers.append(user)

如果希望在给定位置插入数字,则可以使用insert()(例如,位置0):

If you wish to insert a number at a given position, you can use insert() (for example, position 0):

numbers.insert(0, user)

这篇关于如何替换列表中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆