简体   繁体   中英

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,

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.

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

[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]. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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