简体   繁体   English

如何在列表列表中查找某些列表的索引?

[英]How to find the index of certain lists in a list of lists?

I have 50 folders containing the same file name but different contents Data_220_beta_0.1_47.0_53.0ND.csv .我有 50 个包含相同文件名但内容不同的文件夹Data_220_beta_0.1_47.0_53.0ND.csv I am skipping certain folders which is mentioned in list I .我正在跳过列表I中提到的某些文件夹。 Now, when the code scans all the remaining folders, it looks for values which are different and X = [x for x in X if min(x) != max(x)] contains the lists with distinct values.现在,当代码扫描所有剩余的文件夹时,它会查找不同的值,并且X = [x for x in X if min(x) != max(x)]包含具有不同值的列表。 How do I identify the corresponding i values which have distinct list elements?如何识别具有不同列表元素的相应i值? The current and expected outputs are presented.介绍了当前和预期的产出。

from functools import reduce
import pandas as pd

N=50

A=[]
X=[]

I=[8, 11, 19, 37, 40, 42]

for i in range(1,N+1):
    if i in I:
        continue
    
    file_loc =f"C:\\Users\\{i}\\Data_220_beta_0.1_47.0_53.0ND.csv"
    df = pd.read_csv(file_loc)
    A=df["% of Nodes not visited"].to_numpy()
    
    A = [x for x in A if str(x) != 'nan']
    #print(A)
    A = [eval(e) for e in A]
    #print(A)
    
    
    X.append(A)

X = [x for x in X if min(x) != max(x)]
print("i =",i)

The current output is当前的 output 是

i=50

The expected output is预期的 output 是

i=[20,27,37,45,48,50]

I'm gessing that:我猜想:

  • X is a list of lists X是列表的列表
  • you are trying to find the indices of the values of X in X before it was last reassigned , which i is not, as it can only be the last integer (50) yielded by range您试图在X before it was last reassigned找到X中 X 的值的索引, i不是,因为它只能是range产生的最后一个 integer (50)

Here is a reproducible example:这是一个可重现的示例:

X = [[18, 43], [29, 2], None, [3, 3], [45], None, None, [52, 66]]

values = [x for x in X if x and min(x) != max(x)]
print(values)  # [[18, 43], [29, 2], [52, 66]]

indices = [X.index(value) for value in values]
print(indices)  # [0, 1, 7]

So, in your code, you should:因此,在您的代码中,您应该:

  • replace continue by X.append(None)X.append(None)替换continue
  • replace X = [x for x in X if min(x) != max(x)] by values = [x for x in X if x and min(x) != max(x)]X = [x for x in X if min(x) != max(x)]替换为values = [x for x in X if x and min(x) != max(x)]
  • before printing, add indices = [X.index(value) for value in values]在打印之前,添加indices = [X.index(value) for value in values]
  • replace print("i =",i) by print(f"{indices=}") , taking advantage of f-strings用 print print(f"{indices=}")替换print("i =",i) ,利用f-strings

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

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