2017-10-12 74 views
0

我有以下代码(工作代码):如何删除列表中每个元组的每一个第二个字符串?

import csv 

original_list = [('1321', '01'), ('MessageXZY', '02'), ('DescriptionSKS', '03'), ('S7_6', '04'), ('S7_3', '05'), ('0A3B', '06'), ('MessageZYA', '07'), ('DescriptionKAM', '08'), ('9K44', '09'), ('MessageYAL', '10'), 
('DescriptionAUS', '11'), ('S7_2', '12')] 

code_list = ['1321', '0A3B','9K44'] 

grouped_tuples = [] 
for entry in original_list: 
    if entry[0] in code_list: 
     new_tuple = [] 
     new_tuple.append(entry) 
     for i in range(original_list.index(entry)+1, len(original_list)): 
      if(original_list[i][0] not in code_list): 
       new_tuple.append(original_list[i]) 
      else: 
       break 
     grouped_tuples.append(tuple(new_tuple)) 

如果我再补充上:

for entry in grouped_tuples: 
    for item in entry: 
     print (item[1]) 

我得到以下列表:

01 
02 
03 
04 
05 
06 
07 
08 
09 
10 
11 
12 

我想什么do是从元组中移除这些数字。因此,而不是使用上面的代码,我用:

for entry in grouped_tuples: 
    for item in entry: 
     a = grouped_tuples.remove(item[1]) 
print (a) 

但是我得到的消息:ValueError异常:list.remove(X):X不在列表中我知道项[0]是列表就像我刚刚打印的那样。什么导致了这个错误?

+0

元组是不可变的,你无法从它们移除项目 - 您必须创建一个没有该项目的新元组。 – jonrsharpe

+1

您的列表包含元组的元组 –

回答

3

你不一定需要remove的元素,你可以动态创建一个新的元组与所需的值:

>>> new_list = [(i[0],)for i in original_list] 
>>> [('1321',), ('MessageXZY',), ('DescriptionSKS',), ('S7_6',), ('S7_3',), ('0A3B',), ('MessageZYA',), ('DescriptionKAM',), ('9K44',), ('MessageYAL',), ('DescriptionAUS',), ('S7_2',)] 
+0

您也可能不需要创建1元组元组。只需返回'i [0]'而不是'(i [0])' –

+0

@EricDuminil永远不会知道OP是否希望数据以特定格式进行进一步处理。 – ZdaR

+0

我很想知道在Python中看到1元组元组的实际应用。由于元组是不可变的,所以你可以期望调用''[0]''。 –

0

你尝试似乎很令人费解给我。除非我误解了你正在努力达到的目标,否则一个班轮就足够了。

[(k,) for (k,v) in original_list if k in code_list]

0

为了得到一个列表中的元组的第一个元素,一个解决办法是:

对于列表中的每个元组:

  1. 转换的元组列表a
  2. a中的第一个元素存储为列表中的单个元素b 元组

如:

>>> a=[("x","z"),("y","z")] 
>>> b=[(list(x)[0],) for x in a] 
>>> b 
[('x',), ('y',)] 

使用这个概念,你的代码给出:

>>> grouped_tuples 
[(('1321', '01'), ('MessageXZY', '02'), ('DescriptionSKS', '03'), ('S7_6', '04'), ('S7_3', '05')), (('0A3B', '06'), ('MessageZYA', '07'), ('DescriptionKAM', '08')), (('9K44', '09'), ('Messag 
eYAL', '10'), ('DescriptionAUS', '11'), ('S7_2', '12'))] 
>>> #preserve grouped_tuples 
... tmpGroupedTuples=list(grouped_tuples) 
>>> tmpGroupedTuples_len=len(tmpGroupedTuples) 
>>> for i in range(0,tmpGroupedTuples_len): 
...  cOuterTuple=list(tmpGroupedTuples[i]) 
...  cOuterTupleLen=len(cOuterTuple) 
...  newOuterTuple=[] 
...  for j in range(0,cOuterTupleLen): 
...    cInnerTuple=list(cOuterTuple[j]) 
...    newInnerTuple=((cInnerTuple[0],)) 
...    newOuterTuple.append(newInnerTuple) 
...  tmpGroupedTuples[i]=tuple(newOuterTuple) 
... 

tmp_grouped_tuples现在包含包含包含grouped_tuples原内的元组的第一个元素内的元组外的元组:

>>> print(tmpGroupedTuples) 
[(('1321',), ('MessageXZY',), ('DescriptionSKS',), ('S7_6',), ('S7_3',)), (('0A3B',), ('MessageZYA',), ('DescriptionKAM',)), (('9K44',), ('MessageYAL',), ('DescriptionAUS',), ('S7_2',))] 
相关问题