Python 编程序列元素替换

Python Programming sequence element replacement

我需要帮助,我必须创建一个程序,该程序使用列表显示来创建一个包含从 1 到 10 的整数的列表,并按递增顺序输出该列表。然后要求用户输入一个 1 到 10 之间的数字,用缺少的 str 对象替换这个数字,并输出列表。如果用户输入的字符串不代表 1 到 10 之间的整数,它会生成相应的消息来指示这种情况,如示例运行所示:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Enter an integer between 1 and 10 >5
[1, 2, 3, 4, 'gone', 6, 7, 8, 9, 10]

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Enter an integer between 1 and 10 >15
15 is not between 1 and 10

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Enter an integer between 1 and 10 >hello
hello is not a positive integer

我创建了以下代码:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
print(my_list)
a = input('Enter an integer between 1 and 10 >')
b = (a.isalpha())
if int(a)<10 and b == False:
    c = my_list.index(int(a))
    d = my_list.remove(int(a))
    e = my_list.insert(c, 'gone') 
    print(my_list)

elif int(a) and b == False:
    b == True
    print (a, 'is not between 1 and 10')     
else:
     print(str(a), 'is not a positive integer')

但我收到以下错误:

RuntimeErrorElement(RuntimeError,Error on line 6:
    c = my_list.index(int(a))
ValueError: 0 is not in list

)

有谁知道我该如何解决这个问题?

你的short-circuiting错了; and 总是计算第一个条件。它只是第二个条件,因为第一个是 False.

要解决,请将控制流结构更改为:

if b == False and int(a)<10:
    c = my_list.index(int(a))
    d = my_list.remove(int(a))
    e = my_list.insert(c, 'gone') 
    print(my_list)
elif b == False and int(a):
    b == True
    print (a, 'is not between 1 and 10')     
else:
     print(str(a), 'is not a positive integer')

列表可以直接赋值,这里还需要加一个判断数字是否在1到10之间的条件,试试这个:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
print(my_list)
a = input('Enter an integer between 1 and 10 >')

if a.isdigit():
    num = int(a)
    if 1 <= num <= 10:
        index = my_list.index(int(a))
        my_list[index] = "gone"
        print(my_list)
    else:
        print(a, 'is not between 1 and 10')
else:
    print(a, 'is not a positive integer')

我觉得你的逻辑有点过头了。由于它的 python,它很容易用更少的代码行和简单的条件检查来完成。请参阅下面的示例:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(my_list)
a = input('Enter an integer between 1 and 10 >')
try:
    a = int(a)  # Convert string to integer, if its invalid, it raises an exception
    if 1 <= a <= 10 and a in my_list:  # Check for membership and range
        my_list[my_list.index(a)] = "gone"  # replace once
        print(my_list)
    else:
        print(a, 'is not between 1 and 10')
except ValueError:
    print(f'{a} is not a positive integer')