簡體   English   中英

如何刪除屬於元組列表的每個元組的第二個元素?

[英]How to remove the 2nd element of every tuple that belongs to a list of tuples?

我有一個看起來像這樣的元組列表;

ListTuple=[('Tuple1', '2ndElement', '3rdElement', 1L), ('Tuple2', '2ndElement', '3rdElement', 2L)]

我想從該元組列表中的每個元組中刪除第二個元素。 輸出將如下所示;

OutputTuple=[('Tuple1', '3rdElement', 1L), ('Tuple2', '3rdElement', 2L)]

如何在python中完成? 非常感謝你。

OutputTuple = [(a, b, d) for a, b, c, d in ListTuple]

哦,順便說一句,因為這些是元組(不可變的),所以您不能從它們中“刪除”東西。 只創建新的東西。

此解決方案在不假定每個元組中元素數量固定或什至每個元組中元素數量相同的情況下起作用。

ListTuple=[('Tuple1', '2ndElement', '3rdElement', 1L), ('Tuple2', '2ndElement', '3rdElement', 2L)]
output = [((t[0],)+t[2:]) for t in ListTuple]

保留一切,但第二項。

In [4]: [(t[0], t[2], t[3]) for t in ListTuple]
Out[4]: [('Tuple1', '3rdElement', 1L), ('Tuple2', '3rdElement', 2L)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM