简体   繁体   English

如何将 function 应用于列表列表中的列表元素?

[英]how to apply function to a list element within a list of lists?

I have a list of lists.我有一个列表列表。 Here is an example of 2 of the lists inside a list:以下是列表中 2 个列表的示例:

global_tp_old = [[2, 1, 0.8333595991134644],[2, 1, 0.8530714511871338]]

I want to access a dataframe index where the index is specified in the first element of the above list in a list.我想访问一个 dataframe 索引,其中索引是在列表中上述列表的第一个元素中指定的。 At the moment I have tried:目前我已经尝试过:

global_tp_new = []
for element in global_tp_old:
   element[:][0] = df_unique[element[:][0]]
   global_tp_new.append(element)

where df_unique is a pandas dataframe produced like this:其中df_unique是一个 pandas dataframe 像这样产生:

['img1.png', 'img2.png', 'img3.png']

I'm trying to match the first element from the list defined above to the number in df_unique .我正在尝试将上面定义的列表中的第一个元素与df_unique中的数字匹配。

I should get:我应该得到:

'img3.png'

as it's the 3rd element (0 indexing)因为它是第三个元素(0 索引)

However, I get the incorrect output where it essentially returns the first element every time.但是,我得到了不正确的 output ,它基本上每次都返回第一个元素。 It's probably obvious but what do I do to fix this?这可能很明显,但我该怎么做才能解决这个问题?

List comprehension might be useful to apply a function fun to the first element of each list in a list of lists ( LoL ).列表理解可能有助于将 function fun应用于列表 ( LoL ) 中每个列表的第一个元素。

LoL  = [[61, 1, 0.8333595991134644],[44, 1, 0.8530714511871338]]

newL = [fun(l_loc[0]) for l_loc in LoL]

No need to use a Pandas DataFrame.无需使用 Pandas DataFrame。

Remember that your element array is actually a reference into the original list.请记住,您的element数组实际上是对原始列表的引用。 If you modify the list, you'll modify global_tp_old as well.如果您修改列表,您也将修改global_tp_old

Something like this, although you may need to change the dataframe indexing depending on whether you're looking for rows or columns.像这样的东西,尽管您可能需要更改 dataframe 索引,具体取决于您是在查找行还是列。

global_tp_old = [[2, 1, 0.8333595991134644],[2, 1, 0.8530714511871338]]

global_tp_new = []
for element in global_tp_old:
   element = [df_unique.iloc[element[0]]] + element[1:]
   global_tp_new.append(element)

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

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