Python get value from list of tuples
Ngày đăng:
23/01/2022
Trả lời:
0
Lượt xem:
80
Find the tuples containing the given element from a list of tuples in PythonPythonServer Side ProgrammingProgramming A list can have tuples as its elements. In this article we will learn how to identify those tuples which contain a specific search element which is a string. Show With in and conditionWe can design a follow with in condition. After in we can mention the condition or a combination of conditions. ExampleLive Demo listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)] test_elem = 'Mon' #Given list print("Given list:\n",listA) print("Check value:\n",test_elem) # Uisng for and if res = [item for item in listA if item[0] == test_elem and item[1] >= 2] # printing res print("The tuples satisfying the conditions:\n ",res)OutputRunning the above code gives us the following result With filterWe use the filter function along with Lambda function. In the filter condition we use the the in operator to check for the presence of the element in the tuple. ExampleLive Demo OutputRunning the above code gives us the following result Given list: [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)] Check value: Mon The tuples satisfying the conditions: [('Mon', 3), ('Mon', 2)]Pradeep Elance Published on 04-Jun-2020 11:51:18 Previous Page Print Page Next Page Advertisements |