gpt4 book ai didi

python - 如果值相等,则将连续的子列表分组在一起,然后提取具有属性 = 'R' 的值

转载 作者:太空宇宙 更新时间:2023-11-03 19:47:19 25 4
gpt4 key购买 nike

输入数据:

[[30.0, 'P'], [45.0, 'R'], [50.0, 'D']....]
[[10.0, 'R'], [20.0, 'D'], [60.0, 'R']...]
[[42.4, 'R'], [76.0, 'R'], [52.0, 'D']....]

这将是一个包含 float 和字符串的巨大列表列表,如果字符串值等于“R”,我需要根据字符串值将子列表分组在一起。上面的列表列表是通过将数据帧转换为列表生成的(仅供引用)。

所以我必须在属性等于“R”的地方找到浮点值,然后将该值放入子列表中。仅当包含子列表的“R”值属性是连续的时,我们才将数据分组在一起。如果没有,它们应该是自己的子列表。

输出数据:

仅当“R”标签数据彼此相邻时才应该在一起,或者它应该是一个单独的子列表

[[45.0], [10.0], [60.0], [42.4, 76.0]]

最佳答案

如果我理解正确,您希望对输入数组中第二个元素为“R”的每个连续元组进行分组。然后,输出应该是这些组的数组,因为任何具有连续 R 的值组都在输出中以数组形式显示为数组。这应该在 python 中工作:

def group(input_array):
r = []
i = 0
while( i < len(input_array) ):
if(input_array[i][1] == 'R'):
# Figure out how many consecutive R's we have then add the sublist to the return array

group_end_index = i + 1
if(group_end_index >= len(input_array)):
# We've reached the end and have a new group that is one element long
r.append([input_array[i][0]])
break
while(1):
if( input_array[group_end_index][1] != 'R' ):
break
group_end_index += 1

r.append(list(map(lambda x: x[0], input_array[i:group_end_index])))
# + 1 because we know the element at group_end_index does not have an 'R'
i = group_end_index + 1
else:
# Not an 'R', ignore.
i += 1
return r


if __name__ == '__main__':
print(group([[1, 'R'], [2, 'R'], [4, 'A'], [4, 'R']]))

这似乎正在为元素列表执行您想要的操作,其中元素是元组,也称为具有两个元素的列表。

关于python - 如果值相等,则将连续的子列表分组在一起,然后提取具有属性 = 'R' 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60047506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com