繁体   English   中英

如何从列表中删除值并在同一索引处将其更改为另一个值?

[英]How to remove the value from a list and change it at the same index with another value?

我想更新板子以添加玩家输入并删除 position 索引处的值并添加一个新值:

def place_marker(board, marker, position): 
    # Anything false than being in acceptable_values
    index_position = 'Wrong'
    #Keep Asking while the input not in acceptable_values
    while index_position not in ["1",'2','3','4','5','6','7','8',"9"]:     
        index_position = input('Choose a number from 1 to 9: ')     
        if index_position not in ["1",'2','3','4','5','6','7','8',"9"]:
            print('Invalid Input')
        
    position = int(index_position) 
    board.pop(position)

要在同一位置更改列表的值,您只需要通过它的索引来引用它,如下所示:

my_list = [1,2,3,4,5]

my_list[3] = 100   # reference the 4th item (list starts at 0 index)

print(my_list)

返回:

[1, 2, 3, 100, 5]

暂无
暂无

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

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