如何更改python中的运行变量



我正在尝试构建一个程序,在给定元组和整数列表的情况下,如果每个元素都可以除以k,则打印所有元组。重要的是,使用input((输入信息。因此,例如,如果我键入:[(6,24,12(,(60,12,6(,(12,18,21(]和6,输出将是[(6、24、12(。然而,我似乎无法更改运行变量y,也不知道我做错了什么,因为我也没有生成任何输出。除了用你可以在下面的代码中看到的想法来解决问题之外,我很高兴收到其他更有效的建议,因为这对我来说似乎是一个非常复杂的解决方案,我只是想不出其他的东西。非常感谢!

def dos():
temp = True
lista = input()
k = input()
count = 0
lista = lista.split('),(') # split the string into different parts corresponding to the entered tuples
for x in range(len(lista) - 1): # for all elements of the list
for y in range(len(lista[0])): # go through the list elements 
if ((lista[x])[y - 1:y]).isdigit(): #is our sign a number or a comma/something else?
while ((lista[x])[y:y + 1]).isdigit(): # make sure we include numbers with more than one digit
count = count + 1 # count how many digits our number has
y += 1 # skip ahead as to not repeat the following digits
if (int(((lista[x])[y - (count + 1):y])) % int(k)) != 0: # if our number can't be divided by the input
temp = False
count = 0
if temp: # if we did not encounter a number that cant be divided by our integer
print(lista[x])
temp = True

您可以使用regex来匹配元组字符串,也可以识别每个字符串的单个整数,从而创建实际的python元组,您可以检查其可分割条件。

import re
def dos():
lista = input()
k = int(input())

found = []
for items in re.findall(r'([-d, ]+)', lista):
tup = tuple(map(int, re.findall(r'-?d+', items)))
if all([i % k == 0 for i in tup]):
found.append(tup)
return found

最新更新