简体   繁体   English

如何在Python中操作嵌套列表?

[英]How do you manipulate nested lists in Python?

I have a Matrix like the next one, but bigger: 我有一个类似下一个矩阵,但更大的矩阵:

m = [[38, 38,  0],
     [39, 38,  0],
     [40, 38,  0],
     [41, 38,  3],
     [42, 38,  0],
     [43, 38,  4],
     [44, 38,  4],
     [45, 38,  5],
     [38, 39,  0],
     [39, 39,  0],
     [40, 39,  0],
     [41, 39,  3],
     [42, 39,  0],
     [43, 39,  4],
     [44, 39,  4],
     [45, 39,  5],
     [38, 40,  0],
     [39, 40,  0],
     [40, 40,  0],
     [41, 40,  3],
     [42, 40,  0],
     [43, 40,  4],
     [44, 40,  4],
     [45, 40,  5]]

And I would like to change the values of the first two columns in a loop to have make them start in 1. 我想在循环中更改前两列的值,使它们从1开始。

The result would be the following Matrix: 结果将是以下矩阵:

[[1, 1,  0],
 [2, 1,  0],
 [3, 1,  0],
 [4, 1,  3],
 [5, 1,  0],
 [6, 1,  4],
 [7, 1,  4],
 [8, 1,  5],
 [1, 2,  0],
 [2, 2,  0],
 [3, 2,  0],
 [4, 2,  3],
 [5, 2,  0],
 [6, 2,  4],
 [7, 2,  4],
 [8, 2,  5],
 [1, 3,  0],
 [2, 3,  0],
 [3, 3,  0],
 [4, 3,  3],
 [5, 3,  0],
 [6, 3,  4],
 [7, 3,  4],
 [8, 3,  5]]

I'd appreciate a detailed explanation because I am new in python. 我希望得到详细的解释,因为我是python的新手。 :) :)

Assumptions 假设条件

I will answer below, but a good practise on StackOverflow is to show what you already tried, and where you got stuck. 我将在下面回答,但是StackOverflow的一个好习惯是显示您已经尝试过的内容以及卡住的位置。 Also, Python has two major versions at the moment: 2.7 and 3. I don't know which one you're using, so I'll be using examples from Python 3. The major versions do not differ drastically, so there's a good chance the examples will work in both versions. 另外,Python目前有两个主要版本:2.7和3。我不知道您使用的是哪个版本,因此我将使用Python 3中的示例。主要版本没有太大差异,因此有一个不错的选择。这些示例在两个版本中均适用。

As @MK Patel stated in a comment, we are not sure if your matrix has three elements for each row, or just one (malformatted). 正如@MK Patel在评论中指出的那样,我们不确定矩阵中的每一行是否包含三个元素,还是仅包含一个(格式错误)元素。 I am going to assume that you mean [1, 1, 0] instead of [1. 1. 0.] 我将假设您的意思是[1, 1, 0]而不是[1. 1. 0.] [1, 1, 0] [1. 1. 0.] [1. 1. 0.] . [1. 1. 0.]

Answer & Examples 答案与范例

To start, let's say your matrix is in m: m =[[38, 38, 0.], ...] 首先,假设您的矩阵在m中: m =[[38, 38, 0.], ...]

The easiest way to loop over all your rows, is like so: 遍历所有行的最简单方法是:

for row in m:
    # do stuff with row
    print(row[1]) # print second column

The problem with this approach is that you have to keep count of what number of row you are on yourself (for example, each loop you can increment a variable "rowCount"). 这种方法的问题在于,您必须对自己的行数进行计数(例如,每个循环都可以递增变量“ rowCount”)。

To make Python do the work for you here, you can iterate an integer over the length of your matrix. 为了使Python在这里为您完成工作,您可以在矩阵的长度上迭代一个整数。 This is done like so: 这样做是这样的:

for i in range(len(m)):
    # your row is now in m[i]
    print(m[i][1]) # print second column

Here, len(m) equals to the length of your array. 在这里, len(m)等于数组的长度。 range(n) is shorthand for a list containing [0, 1..., n]. range(n)是包含[0,1 ...,n]的列表的简写。 This way, you can set your rows' first column (index 0) to match the row count, so this column starts at 1, and goes up together with your loop. 这样,您可以将行的第一列(索引0)设置为与行数匹配,因此此列从1开始,并随循环一起上升。 Keep in mind that Python (and most other programming languages) will start counting at 0, so you will have to add 1 each time. 请记住,Python(和大多数其他编程语言)将从0开始计数,因此您每次必须加1。

Since you want to "restart" your count for every new value in the second column, you can use the modulo ( % ) operator to make i restart at 1 every time it goes up by 8. This is based on an assumption I made about your second column. 由于您想“重新启动”第二列中每个新值的计数,因此可以使用模( % )运算符使我每次上升8时就从1重新开始。这是基于我对您的第二列。 Read more in the next paragraph. 在下一段中阅读更多内容。

for i in range(len(m)):
    # set first column to i + 1, to start counting from 1 and go up every time
    m[i][0] = (i % 8) + 1

For your second column, I am also missing some information. 对于您的第二栏,我也缺少一些信息。 There are a few approaches to your problem, depending on what is always true. 有几种方法可以解决您的问题,具体取决于始终是什么。 The most noticable thing is that every number repeats 8 times, so I will use this fact in the code. 最值得注意的是每个数字重复8次,因此我将在代码中使用这个事实。

We can use the integer devision operator ( // ) to add one for every 8 that our iterator ( i ) goes up. 我们可以使用整数除法运算符( // )在迭代器( i )上升的每8个数字中添加一个。

for i in range(len(m)):
    # set first column to i + 1, to start counting from 1 and go up every time
    m[i][0] = (i % 8) + 1
    # set the second column to (i // 8) + 1, going up one every 8 rows (and start at one)
    m[i][1] = (i // 8) + 1

I hope this helped. 希望对您有所帮助。

You can solve it in one line of code in python... This method call as comprehension method... Your solution is... 您可以在python的一行代码中解决该问题...此方法称为理解方法...您的解决方案是...

final_matrix = [[inner_matrix[0]-37, inner_matrix[1]-37, inner_matrix[2]] for inner_matrix in m]

print(final_matrix)

and if you are new in python then you can solve it as other language like... 如果您是python的新手,则可以将其作为其他语言来解决,例如...

result= []
for inner_matrix in m:
    inner_matrix[0] -= 37
    inner_matrix[1] -= 37
    result.append(inner_matrix)

print(result)

Note:- Above solution is not a good practice for python..this is only for your easy understanding...in real you should solve it using comprehension method. 注意:-上述解决方案对于python来说不​​是一个好习惯。.这仅是为了您的简单理解...实际上,您应该使用理解方法来解决它。

If you dont know about comprehension method then.... Read topic 5.1.3 如果您不了解理解方法,那么.... 阅读主题5.1.3

If you know the first cell contains the minimal value, a simple way is to iterate over all the rows and modify the first X columns by subtracting the minimal value. 如果您知道第一个单元格包含最小值,则一种简单的方法是遍历所有行并通过减去最小值来修改前X列。

In other words, in your example, the minimal value is 38, so you just need to subtract 37 to the first two columns. 换句话说,在您的示例中,最小值为38,因此您只需要在前两列中减去37。

Let's say your matrix is m , the complete code is: 假设您的矩阵是m ,完整的代码是:

# get the value that will be translated to 1
# the - 1 is here to start at 1, not 0
start_val = m[0][0] - 1

# iterate over all the rows
for row in m:
    # iterate over the first 2 columns
    for i in range(2): # i = 0, i = 1
        # change the value
        row[i] -= start_val 

Note that in this snippet, we modify the matrix "inplace", ie directly. 请注意,在此代码段中,我们直接修改了矩阵“ inplace”。


Just for fun, this could also be done using this one-liner (see the list comprehension concept in functional python programming): 只是为了好玩,也可以使用这种单行代码来完成此操作(请参见功能性python编程中的列表理解概念 ):

start_val = m[0][0] - 1
new_m = [[c-start_val for c in row[:2]] + row[2:] for row in m]

A more general approach would be to use Python list comprehension. 更通用的方法是使用Python列表理解。

You can do what you want to each of the columns independently. 您可以对每个列分别执行所需的操作。 The following example does exactly what you want... 以下示例完全满足您的要求...

new_matrix = [[i[0]-37, i[1]-37, i[2]] for i in a]

Where the number 37 can be determined from the initial list if you don't want to hard code it. 如果您不想对其进行硬编码,则可以从初始列表中确定数字37的位置。

Here is a good tutorial on how list comprehension works in Python. 这是一个很好的教程 ,介绍了列表推导如何在Python中工作。

You can try this simple one: 您可以尝试以下简单的方法:

my_list = [[38, 38, 0, ],
           [39, 38, 0, ],
           [40, 38, 0, ],
           [41, 38, 3, ],
           [42, 38, 0, ],
           [43, 38, 4, ],
           [44, 38, 4, ],
           [45, 38, 5, ],
           [38, 39, 0, ],
           [39, 39, 0, ],
           [40, 39, 0, ],
           [41, 39, 3, ],
           [42, 39, 0, ],
           [43, 39, 4, ],
           [44, 39, 4, ],
           [45, 39, 5, ],
           [38, 40, 0, ],
           [39, 40, 0, ],
           [40, 40, 0, ],
           [41, 40, 3, ],
           [42, 40, 0, ],
           [43, 40, 4, ],
           [44, 40, 4, ],
           [45, 40, 5, ], ]

first_column = 1
second_column = 1
for i in range(len(my_list)):
    if first_column > 8: #if value of first column is greater than 8 then reset first_column and second_column
        first_column = 1
        second_column = second_column + 1
    my_list[i][0] = first_column
    my_list[i][1] = second_column
    first_column = first_column + 1

print(my_list)
  • Iterate through the list 遍历list
  • Change the value of the first and second column 更改第一列和第二列的值
  • If value of first_column is greater than 8 then increment value of second_column and make first_column=1 如果first_column的值大于8,则增加second_column值并使first_column=1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM