简体   繁体   English

在列表中查找元组

[英]Finding tuples in a list

I'm confused on how to find tuples within a list and remove the tuples as well as the value inside of it in python for example,例如,我对如何在列表中查找元组并在 python 中删除元组以及其中的值感到困惑,

mylist = [12, 'Mark', 34.23(45)]

Output = [12, 'Mark', 34.23]

If the list had multiple tuples everywhere, how would I go about this?如果列表到处都有多个元组,我将如何处理? Thanks!谢谢!

Using functional approach if you have tuples in a list, you canapply a filter with a function which returns true for all except tuples.如果列表中有元组,则使用函数式方法,您可以应用带有函数的过滤器,该函数对除元组之外的所有元组都返回 true。

my_list = [12, 'Mark', (34.23,45)]
filter_obj= filter(lambda x: not isinstance(x,tuple), my_list)
#above line is equvalent to (x for x in my_list if not isinstance(x, tuple)) which returns a generator 
processed_list = list(filter_obj)

Or you can generate a list directly usng list comprehension.或者您可以直接使用列表理解生成列表。

my_list = [12, 'Mark', (34.23,45)]
processed_lsit = [x for x in my_list if not isinstance(x,tuple)]

You can just check the type of list elements, and if it is of type tuple, simply remove it.您可以只检查列表元素的类型,如果它是元组类型,只需将其删除。 Considering your list to be考虑到你的清单是

mylist = [12, 'Mark', (34.23, 45)]
for i in mylist:
    if type(i) == tuple:
        mylist.remove(i)

After this code executes, mylist is updated to此代码执行后, mylist更新为

[12, 'Mark']

As Michael said the code is incorrect.正如迈克尔所说,代码不正确。 But in case you have tuples in a list, for example [12, 'Mark', (34.23,45),21].但如果列表中有元组,例如 [12, 'Mark', (34.23,45),21]。 This could be removed checking for the "type" of the elements present in the list.这可以删除检查列表中存在的元素的“类型”。

mylist = [12, 'Mark', (34.23,45),21]

for elements in mylist:
    if str(type(elements)) in "<class 'tuple'>":
        mylist.remove(elements)

print(mylist)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM