As part of my homework I have to access every element oa list without a for loop to use it in a function I'm allowed to use, eg:
myList=['Hello','World']
I've tried using lambda functions (Because I'm not allowed to declare functions with Def) but didn't work.
function(next(myList))
Also tried using next(myList) but sometimes the list can have 1000+ elements.
Use lambda with map for apply a function to each element:
myList=['Hello','World']
list(map(lambda x: x.upper(), myList))
Using map is the shortest way to do it. You don't need lambda.
li = list(range(10)) # this is your list
list(map(print, li)) # view each element
If you can use function you can use that trick
You can use recursion to access all elements.
At first create a function to read first element and delete that element.
Use that function again and again until the list is empty.
def show(my_list):
try:
print(my_list[0])
del my_list[0]
show(my_list)
except:
pass
Or if you want to do some action
new = []
def action(my_list):
try:
x = do_something(my_list[0])
del my_list[0]
new.append(x)
action(my_list)
except:
pass
Here do_something(data)
is your custom function.
I believe the cleanest way to do this is with a map
function:
l = [1,2,3]
list(map(lambda x : print(x), l))
# returns
# >> 1
# >> 2
# >> 3
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.