输入数据:
[[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']....]这将是一个包含一个浮点数和一个字符串的巨大列表,如果字符串值等于'R‘,我需要根据字符串值将子列表分组在一起。上面的列表是通过将数据帧转换为列表生成的(仅供参考)。
因此,我必须在属性等于'R‘的地方找到浮点值,然后将该值放在子列表中。只有当包含子列表的'R‘值属性是连续的时,我们才将数据分组在一起。如果不是,它们应该是自己的子列表。
输出数据:
只有当'R‘标记数据彼此相邻或者应该是一个单独的子列表时,它们才应该放在一起
[[45.0], [10.0], [60.0], [42.4, 76.0]]发布于 2020-02-04 05:50:53
def group_consecutive( lists, char ) :
result = []
# For each list
for l in lists :
local_result = []
# For each element in list
for n, c in l :
# Check if char is the same
if c == char :
local_result.append(n)
# Else, if local_result has any element
elif local_result :
result.append( local_result )
local_result = []
# FIX: Append last result if not empty
if local_result :
result.append( local_result )
return result
l1 = [[30.0, 'P'], [45.0, 'R'], [50.0, 'D']]
l2 = [[10.0, 'R'], [20.0, 'D'], [60.0, 'R']]
l3 = [[42.4, 'R'], [76.0, 'R'], [52.0, 'D']]
result = group_consecutive( [ l1, l2, l3 ], 'R' )
print( result )前面的代码给出了以下输出:
[[45.0], [10.0], [60.0] [42.4, 76.0]]发布于 2020-02-04 05:55:00
您可以使用for循环:
input_data = [
[[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']]]
final_list = []
new_list = []
for l in [e for e in input_data]:
if new_list:
final_list.append(new_list)
new_list = []
for value, tag in l:
if tag == 'R':
new_list.append(value)
elif new_list:
final_list.append(new_list)
new_list = []
print(final_list) 输出:
[[45.0], [10.0], [60.0], [42.4, 76.0]]发布于 2020-02-04 07:12:52
如果我理解正确的话,您希望对输入数组中以'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']]))这似乎是在为元素列表做你想要的事情,其中的元素是元组,也就是包含两个元素的列表。
https://stackoverflow.com/questions/60047506
复制相似问题