简体   繁体   English

如何在 Python 的列表中替换列表中的项目

[英]How to replace item in lists in a list in Python

Now i just want to replace the min, max value with the x in the table.... and i dont know how to...现在我只想用表中的 x 替换最小值、最大值......而且我不知道如何......

for i in table[1:]:
    mn = min(i) if min(i) < mn else mn 
    mx = max(i) if max(i) > mx else mx
    x = (mn+mx)/2

The following should work:以下应该有效:

def remove_outliers(table):
    mx = max(map(max, table))
    mn = min(map(min, table))
    avg = (mx + mn) / 2

    for row in table:
        row[:] = [avg if x in (mx, mn) else x for x in row]
    # OR
    for row in table:
        for i, x in enumerate(row):
            if x in (mx, mn):
                row[i] = avg

max(map(max, table)) : applies the max function to each row in table , and takes the max of all those "maxes". max(map(max, table))max function 应用于table中的每一行,并取所有这些“ max ”中的最大值。

row[:] =... : slice-assignment. row[:] =...切片分配。 This is a mutation on the row object.这是 object row上的突变。 Simply row =... would just rebind the loop variable without affecting the list object that is still indexed by table .只需row =...只会重新绑定循环变量,而不会影响仍由table索引的列表 object 。

[avg if x in (mx, mn) else x for x in row] : general conditional list comprehension. [avg if x in (mx, mn) else x for x in row]一般条件列表理解。 Fairly self-explanatory.相当不言自明。

If you are using numpy check out the clip function ( https://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html ). If you are using numpy check out the clip function ( https://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html ).

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

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