简体   繁体   English

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

[英]How to check if a sequence of integers is in a list

I want the program to continue executing until every element on the list is a string.我希望程序继续执行,直到列表中的每个元素都是一个字符串。
That is那是

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

should stop when应该在什么时候停止

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

This is what I have tried, but if the first[0] and and last[7] element becomes a string, the while loop goes to the last else condition even with int type present in the list.这是我尝试过的,但是如果first[0]last[7]元素变成一个字符串,while 循环会转到最后一个 else 条件,即使列表中存在int类型。 if done sequentially, it works fine.如果按顺序完成,它工作正常。

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)

But, I don't want it sequentially.但是,我不希望它按顺序进行。
Therefore, it should continue if因此,它应该继续,如果

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

and stop when并在什么时候停止

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

all strings所有字符串

You can use all or any in conjunction with string.isnumeric() to check this您可以将allanystring.isnumeric()结合使用来检查这一点

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

The solution you asked for is possible.您要求的解决方案是可能的。 But one piece of advice while writing in python, is to avoid doing type checking explicitly (type(a) == int).但是在用 python 编写时的一条建议是避免显式地进行类型检查 (type(a) == int)。 below is a simple solution.下面是一个简单的解决方案。

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)

I think you can do this:我认为你可以这样做:

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

Geckos gave me a clue.壁虎给了我一个线索。 Thank you for that.谢谢你。 I found out that using isinstance with any() solves the problem我发现使用 isinstance 和 any() 解决了这个问题

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

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

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