我有这样的数据列表:
data = ['Data_0',
['param_1', 0],
['param_2', 1],
['param_3', 3.14],
['param_n', 375],
['param_6' , 67],
'Data_1',
['param_1', 1],
['param_2', 2],
['param_3', 3.4],
['param_n', 6785],
['param_6',678],
'Data_2',
['param_1', 1],
['param_2', 3],
['param_3', 2.19],
['param_n', 345],
['param_6', 675]]
我需要像这样分割数据列表的代码:
sliced_data_0 = [
'Data_0',
['param_1', 1],
['param_2', 2],
['param_3', 3.4],
['param_n', 6785],
['param_6',678],
sliced_data_1 = [
'Data_1',
['param_1', 1],
['param_2', 2],
['param_3', 3.4],
['param_n', 6225],
['param_6',678],
sliced_data_2 = [
'Data_2',
['param_1', 1],
['param_2', 2],
['param_3', 3.4],
['param_n', 12385],
['param_6',623],
我需要一些可以循环运行的代码
for i in data:
update_method(sliced_data_[i])
预先感谢,堆叠!在此先感谢,堆叠!预先感谢,堆叠!预先感谢,堆叠!
答案 0 :(得分:1)
如果您知道要拆分的子列表的长度,则可以将yield
与香草python结合使用。从函数中调用此函数并在list()
中捕获结果,即可将数据切成碎片。
def slicep(arr):
for i in range(0, len(arr), 4):
yield arr[i:i + 4]
def update_method(arr):
print(arr)
data = [1,[2, False],[3, 1],[4, 3.14],5,[6, True],[7, 0],[8, 2.19],9,[0, False],[1, 1],[2, 6.12]]
sliced_data = list(slicep(data))
for sublist in sliced_data:
update_method(sublist)
您可以将list()
的结果捕获到一个变量中,该变量将成为切片列表的列表。然后,您可以遍历此条目,并在每个条目上调用update_method()
。
答案 1 :(得分:1)
for i in range(0, len(data), 4):
update_method(data[i:i+4])
或
for sub_data in zip(*(data[i::4] for i in range(4)))):
update_method(sub_data)
答案 2 :(得分:0)
谢谢你们! 我刚刚添加了用于切片的计数线的方法:
def line_counter(data):
block_count = 0
line_count = 0
for string in data:
if type(string) is str:
block_count += 1
if type(string) is list and block_count == 1:
line_count += 1
return line_count
def slicer(data, count_of_lines_in_data):
for string in data:
if type(string) is str:
data.remove(string)
for i in range(0, len(data), count_of_lines_in_data):
yield data[i:i + count_of_lines_in_data]
def update_method(sublist):
print(sublist)
if __name__ == "__main__":
data = ['Data_0',
['param_1', 0],
['param_2', 1],
['param_3', 3.14],
['param_n', 375],
['param_6' , 67],
'Data_1',
['param_1', 1],
['param_2', 2],
['param_3', 3.4],
['param_n', 6785],
['param_6',678],
'Data_2',
['param_1', 1],
['param_2', 3],
['param_3', 2.19],
['param_n', 345],
['param_6', 675]]
count_of_lin = line_counter(data)
sliced_data = list(slicer(data, count_of_lin))
for sublist in sliced_data:
update_method(sublist)
这是必需的,因为数据列表中的参数数量不是4,而是可以变化的。