Python, two dimensional list and coordinates

后端 未结 1 1471
名媛妹妹
名媛妹妹 2021-01-26 11:53

I have a two dimensional list:

def list():
    list1 =[1,2,3,4,5]
    list2 =[0,0,0,0,0]
    list3 =[6,7,8,9,10]

    list=[list1,list2,list3]

    for i in list         


        
相关标签:
1条回答
  • 2021-01-26 12:13

    Just assign directly to those two index pairs, indexing from the outer list to the inner (the last list is 2, the middle list is 1), so the first element of the last list is at [2][0]:

    outerlist[1][0], outerlist[2][0] = outerlist[2][0], 0
    

    This assigns two values (one taken from outerlist[0][2], the other the literal 0 integer) to the two positions in the nested lists.

    If you wanted to swap those two positions (taking the 0 from outerlist[0][1]), then do so with the same syntax:

    outerlist[1][0], outerlist[2][0] = outerlist[2][0], outerlist[1][0]
    

    because the right-hand side expression is evaluated before assigning the two values to the left-hand side targets:

    >>> outerlist = [[1, 2, 3, 4, 5], [0, 0, 0, 0, 0], [6, 7, 8, 9, 10]]
    >>> outerlist
    [[1, 2, 3, 4, 5], [0, 0, 0, 0, 0], [6, 7, 8, 9, 10]]
    >>> outerlist[1][0], outerlist[2][0] = outerlist[2][0], outerlist[1][0]
    >>> outerlist
    [[1, 2, 3, 4, 5], [6, 0, 0, 0, 0], [0, 7, 8, 9, 10]]
    
    0 讨论(0)
提交回复
热议问题