![](/img/trans.png)
[英]Python | How to group value to different lists from a main list given a certain range of number for each index
[英]How to delete certain number from a list in list using the index in python?
我在列表中有一个列表,我试图删除每个子列表的第三个数字,但每次我都收到错误TypeError: list indices must be integers or slices, not list
a = [[0.0, 0.0, 0.0], [0.19, 0.36, 0.0], [0.24, 0.42, 0.0], [0.16, 0.08, 0.0], [0.05, -0.57, 0.0] ]
期望的结果:-
a_updated = [[0.0, 0.0], [0.19, 0.36], [0.24, 0.42], [0.16, 0.08], [0.05, -0.57] ]
在我的代码的第二部分,我想根据下面显示的字典合并这个子列表,例如,字典的第一个值:- 1: [1, 2]
显示第一个和第二个值的合并,即[0, 0, 0.19, 0.36]
。
我想我的这部分代码是正确的!
dict_a = { {1: [1, 2], 2: [2, 4], 3: [3, 5], 4: [4, 5] }
我的尝试:-
dict_a = { 1: [1, 2], 2: [2, 4], 3: [3, 5], 4: [4, 5]}
a = [[0.0, 0.0], [0.19, 0.36], [0.24, 0.42], [0.16, 0.08], [0.05, -0.57]]
# first part
for i in a:
for j in a[i]:
del j[2]
print(j)
#second part
a_list = []
list_of_index = []
for i in dict_a:
index= []
a_list.append(index)
for j in dict_a_updated[i]:
print(j-1)
index.extend(a_updated[j-1])
print('index',index)
错误 output -
file "D:\python programming\random python files\4 may axial dis.py", line 18, in <module>
for j in X[i]:
TypeError: list indices must be integers or slices, not list
您可以在列表理解中对子列表进行切片以构建a_updated
:
a_updated = [s_lst[:2] for s_lst in a]
Output:
[[0.0, 0.0], [0.19, 0.36], [0.24, 0.42], [0.16, 0.08], [0.05, -0.57]]
要构建dict_a_updated
,您可以使用循环。 请注意,列表索引从 Python 中的 0 开始,但您的索引从 1 开始,因此我们必须在此处减去 1:
dict_a_updated = {}
for k, v in dict_a.items():
tmp = []
for i in v:
tmp.extend(a_updated[i-1])
dict_a_updated[k] = tmp
Output:
{1: [0.0, 0.0, 0.19, 0.36],
2: [0.19, 0.36, 0.16, 0.08],
3: [0.24, 0.42, 0.05, -0.57],
4: [0.16, 0.08, 0.05, -0.57]}
给定列表列表:
a = [[0.0, 0.0, 0.0], [0.19, 0.36, 0.0], [0.24, 0.42, 0.0], [0.16, 0.08, 0.0], [0.05, -0.57, 0.0]]
第一种解法:如果第三个元素是所有arrays中的最后一个元素。
firstSolution = [el[:-1] for el in a]
print(firstSolution)
第二种解决方案:是通过其索引删除元素。
for el in a:
el.pop(2)
print(a)
您可以通过单个字典理解和itertools.chain
实现您的目标,而无需先返工a
:
from itertools import chain
out = {k: list(chain.from_iterable(a[i-1][:2] for i in v))
for k,v in dict_a.items()}
Output:
{1: [0.0, 0.0, 0.19, 0.36],
2: [0.19, 0.36, 0.16, 0.08],
3: [0.24, 0.42, 0.05, -0.57],
4: [0.16, 0.08, 0.05, -0.57]}
a = [[0.0, 0.0, 0.0], [0.19, 0.36, 0.0], [0.24, 0.42, 0.0], [0.16, 0.08, 0.0], [0.05, -0.57, 0.0] ]
dict_a = {1: [1, 2], 2: [2, 4], 3: [3, 5], 4: [4, 5] }
# first part
for i in range(0,len(a)): # for every sublist position
a[i] = a[i][0:2]
dict_lists = {}
for key,value in dict_a.items():
dict_lists[key] = [a[value[0]-1], a[value[1]-1]]
Output:
In[19]: dict_lists
Out[19]:
{1: [[0.0, 0.0], [0.19, 0.36]],
2: [[0.19, 0.36], [0.16, 0.08]],
3: [[0.24, 0.42], [0.05, -0.57]],
4: [[0.16, 0.08], [0.05, -0.57]]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.