我正在嘗試構建一個程式,給定一個元組串列和一個整數,列印所有元組,每個元素都可以除以 k。重要的是,使用 input() 輸入資訊。例如,如果我輸入:[(6, 24, 12),(60, 12, 6),(12, 18, 21)] 和 6,輸出將是 [(6, 24, 12),( 60, 12, 6)]。但是,我似乎無法更改運行變數 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
uj5u.com熱心網友回復:
您可以使用正則運算式來匹配元組字串,還可以使用每個字串識別單個整數,從而創建實際的 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/511283.html
標籤:Python列表表现变量
上一篇:在序言中使用變數設定聯合
下一篇:如何使變數成為條件?
