如何在Python中以多种方式遍历列表和元组?

时间:2016-02-14 02:01:30

标签: list loops tuples python-3.5 magic-square

我是Python新手。我不会隐藏这是家庭作业。我无法找到迭代多个列表的方法。

我最初为一个列表编写了以下编码(' lst'),它完美无缺!然后我回去添加其他三个列表,我不知道为什么我不能让它工作。

我们非常感谢任何建议。如果有关于清洁和重构的任何提示,我会很感激!

 result='False'

 def magic(lst):
    count=0
    #Create a list.
    if count == 0:
        lst=[(4,9,2),(3,5,7),(8,1,6)]
        count==1
        result='True'
    elif count==1:
        lst=[(2,7,6),(9,5,1),(4,3,8)]
        count==2
        result='True'
    elif count==2:
        lst=[(1,2,3),(4,5,6),(7,8,9)]
        count==3
        result='True'
    else:
        lst=[(4,9,2),(3,5,5),(8,1,6)]
        result='True'
    return result 

    #set condition for magic square and print results
    if is_row(let) and is_col(let) and is_diag(lst):
        print('True')
    else:
        print("False")

#is_row function accepts a list as argument returns true or false       
def is_row(lst):
   if sum(lst[0]) == sum(lst[1]) == sum(lst[2]):
       result_R = True
   else:
       result_R = False
   return result_R

#is_col does the same thing as is_row

def is_col(lst):
    for i in lst:
        #select from the tuples in lst to make columns list
        col1=[i[0] for i in lst]

        col2=[i[1] for i in lst]

        col3=[i[2] for i in lst]

        if sum(col1) == sum(col2) == sum(col3):
            result_C = True
        else:
            result_C = False
        return result_C

def is_diag(lst):
    #unpack all tuples into single list for easier indexing.
    unpack1=[num for element in lst for num in element]
    #Diagonal one slice
    D1=unpack1[0:9:4]
    #reverse list...simpler way of preparing for Diagonal Two
    lst.reverse()
    #unpack the reversed list
    unpack2=[num for element in lst for num in element]
    #Diagonal 2 slice
    D2=unpack2[0:9:4]
    #Condition for sum comparison
    if sum(D1)==sum(D2):
        result_D = True
    else:
        result_D = False
    return result_D

magic(a,b,c,d)

0 个答案:

没有答案