我希望程序继续执行,直到列表上的每个元素都是字符串为止。
那是
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]
和and 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]
所有字符串
答案 0 :(得分:1)
您可以结合使用all
或any
与string.isnumeric()
进行检查
li = ['a', 1, 2]
while any(str(ele).isnumeric() for ele in li):
modify li ...
答案 1 :(得分: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)
答案 2 :(得分: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
答案 3 :(得分:0)
壁虎给了我一个线索。谢谢你我发现将isinstance与any()一起使用可以解决问题
li = ['a', 1, 2]
while any(isinstance(element, int) for element in li):
#code goes here...