Skip to main content
 首页 » 编程设计

python之如何检查整数序列是否在列表中

2024年11月24日9softidea

我希望程序继续执行,直到列表中的每个元素都是字符串。
那就是

li = [1, 2, 6, 'h', 'y', 'h', 'y', 4] 

应该在什么时候停止

li = [all elements type are strings] 
li = [1, 2, 6, 'h', 'y', 'h', 'y', 4] 
 
while '''there are still numbers in the list''': 
    #code keeps on executing and updating li[] with string input 
else: 
    # output the list with no numbers 

这是我试过的方法,但是如果 first[0] 和 last[7] 元素变成字符串,while 循环会转到最后一个 else即使 int 类型存在于列表中。如果按顺序完成,则效果很好。

li = [8, 2, 6, 'h', 'y', 'h', 'y', 4] 
 
for a in li: 
    while a in li: 
        if type(a) == int: 
            x = int(input('Position: ')) 
            entry = input('Enter: ') 
            li.pop(x) 
            li.insert(x, entry) 
            print(li) # to see what's happening 
            li = li 
    else: 
        print('Board is full') 
 
print(li) 

但是,我不想按顺序。
因此,如果

li = [c, 2, 6, 'h', 'y', 'h', 'y', f] 

然后停止

li = [a, b, c, 'h', 'y', 'h', 'y', d] 

所有字符串

请您参考如下方法:

您可以使用 all 或 any 结合 string.isnumeric() 来检查这个

li = ['a', 1, 2] 
while any(str(ele).isnumeric() for ele in li): 
    modify li ...