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

3

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

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]元素变成字符串,即使在列表中有int类型,while循环也会进入最后一个else条件。 如果按顺序完成,则可以正常工作。
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]

所有字符串


创建一个类型为(x)==int的lambda函数,将其与内置函数“all”一起使用(对于大型列表而言计算密集度较高,但在此处可以接受)。 - Kenny Ostrom
你的整个循环应该是“while not done”,因此不需要其他循环机制,如果我理解正确的话。现在,你的while循环什么也没做 - 它只是检查a是否在li中,这总是true,因为你从li中得到了a并且从未改变它。 - Kenny Ostrom
你是对的 @KennyOstrom。条件始终保持为真。 - Chris Josh
4个回答

1
你可以使用allanystring.isnumeric()一起来检查这个。
li = ['a', 1, 2]
while any(str(ele).isnumeric() for ele in li):
    modify li ...

1
谢谢,虽然这对我没用,但你给了我一个起点 :-) - Chris Josh

0
你所要求的解决方案是可行的。但是在编写Python代码时,一个建议是避免显式地进行类型检查(type(a) == int)。下面是一个简单的解决方案。
import string
import random
letter = random.choice(string.ascii_letters) #swapping data
xe = [8, 2, 6, 'h', 'y', 'h', 'y', 4]
for i in range(len(xe)):
    try:
        xe[i].upper()
    except:
        xe.pop(i)
        xe.insert(i,letter)
print(xe)

1
你应该避免使用裸露的 except,因为它会捕获像 SystemExit 这样的东西。 - gmds
已经注意到 @gmds - Christopher_Okoro
1
这让我觉得try/except的使用非常奇怪。调用upper除了扮演隐式类型检查的作用外什么也没做 - 显式比隐式更好。只需执行if not isinstance(xe[i], str):(在Python 2中使用basestr)即可。而且pop+insert操作可以更清晰简洁地写成xe[i] = letter - Nathan Vērzemnieks
感谢Nathan的巨大贡献,这非常有帮助。不过我想,通过使用对象方法(在这种情况下是upper),与其进行类型检查,这样会更有帮助。还要感谢您提供的关于pop + insert的提示。 - Christopher_Okoro

0

我认为你可以做到这一点:

li = [1, 2, 3, h, y, 5, g, 3]
length = len(li)
while count != length:
    for row in li:
    if type(row) == int:
        li.pop(row)
        count += 1

0

壁虎给了我一个线索。非常感谢你。我发现使用isinstance与any()解决了这个问题。

li = ['a', 1, 2]
while any(isinstance(element, int) for element in li):
       #code goes here...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接