从 Python 中的子列表列表中删除具有固定百分比的元素
Remove elements with fixed percentage from a list of sub-lists in Python
我有以下列表:
list = [[0.002, 0.001, 0.055, 0.44, 0.11, 0.002, 0.001, 0.055, 0.44, 0.11],
[0.001, 0.006, 0.009, 0.002, 0.33],
[0.02, 0.004,0.003, 0.001, 0.008]]
我想为每个子列表保留 20% 的元素,并从子列表的开头删除列表元素,因此结果如下:
list = [[0.055, 0.44, 0.11, 0.002, 0.001, 0.055, 0.44, 0.11],
[0.006, 0.009, 0.002, 0.33],
[0.004,0.003, 0.001, 0.008]]
我写了下面的代码:
def del_list_rate(list):
list_del = []
n = 0.2
d = int(le * (1 - n))
for list1 in list:
le = len(list1)
d = int(le * (1 - n))
del list1[0 : le-d]
list_del.append(list1)
有什么方法可以更快地编码吗?
In [8]: list
Out[8]:
[[0.002, 0.001, 0.055, 0.44, 0.11, 0.002, 0.001, 0.055, 0.44, 0.11],
[0.001, 0.006, 0.009, 0.002, 0.33],
[0.02, 0.004, 0.003, 0.001, 0.008]]
In [9]: [i[int(0.2 * len(i)):] for i in list]
Out[9]:
[[0.055, 0.44, 0.11, 0.002, 0.001, 0.055, 0.44, 0.11],
[0.006, 0.009, 0.002, 0.33],
[0.004, 0.003, 0.001, 0.008]]
为了改进 bigbounty 的答案,我建议使用以下方法:
def del_list_rate(list):
return [sublist[int(0.2 * len(sublist)):] for sublist in list]
我有以下列表:
list = [[0.002, 0.001, 0.055, 0.44, 0.11, 0.002, 0.001, 0.055, 0.44, 0.11],
[0.001, 0.006, 0.009, 0.002, 0.33],
[0.02, 0.004,0.003, 0.001, 0.008]]
我想为每个子列表保留 20% 的元素,并从子列表的开头删除列表元素,因此结果如下:
list = [[0.055, 0.44, 0.11, 0.002, 0.001, 0.055, 0.44, 0.11],
[0.006, 0.009, 0.002, 0.33],
[0.004,0.003, 0.001, 0.008]]
我写了下面的代码:
def del_list_rate(list):
list_del = []
n = 0.2
d = int(le * (1 - n))
for list1 in list:
le = len(list1)
d = int(le * (1 - n))
del list1[0 : le-d]
list_del.append(list1)
有什么方法可以更快地编码吗?
In [8]: list
Out[8]:
[[0.002, 0.001, 0.055, 0.44, 0.11, 0.002, 0.001, 0.055, 0.44, 0.11],
[0.001, 0.006, 0.009, 0.002, 0.33],
[0.02, 0.004, 0.003, 0.001, 0.008]]
In [9]: [i[int(0.2 * len(i)):] for i in list]
Out[9]:
[[0.055, 0.44, 0.11, 0.002, 0.001, 0.055, 0.44, 0.11],
[0.006, 0.009, 0.002, 0.33],
[0.004, 0.003, 0.001, 0.008]]
为了改进 bigbounty 的答案,我建议使用以下方法:
def del_list_rate(list):
return [sublist[int(0.2 * len(sublist)):] for sublist in list]