Try

lambda x: 1 if x == "C" else 0

possible duplicate of Is there a way to perform "if" in python's lambda

Example :

map(lambda x: True if x % 2 == 0 else False, range(1, 11))

result will be - [False, True, False, True, False, True, False, True, False, True]

Answer from pnv on Stack Overflow
Discussions

dictionary - Python - How to use map function and lambda function with if condition - Stack Overflow
I want to compare the wordlist and the checklist by using map function and lambda function if the words in wordlist and checklist. this words will be deleted in wordlist. Anyone can help me? thanks... More on stackoverflow.com
🌐 stackoverflow.com
Usage of map function correctly with an if statement for python - Stack Overflow
I tried to use map correctly and used and if statement to make sure that if the list was empty to not proceed and stop. I will display the input as well. For clarification, numbers_1 function is wh... More on stackoverflow.com
🌐 stackoverflow.com
python - Lambda with if condition in map() - Stack Overflow
pass is a statement, but inline ... map can’t actually remove elements from the sequence, but filter (returns a new list with only the values for which the function returns True) can: ... Sign up to request clarification or add additional context in comments. ... Save this answer. ... Show activity on this post. If you're like me and don't like filters and lambda, you can accomplish this with Python list ... More on stackoverflow.com
🌐 stackoverflow.com
April 9, 2017
python - How to use map function with condition? - Stack Overflow
How can I use map function in python for multiprocessing, I want to apply the above code in Pool function · pool = Pool(processes=5) pool.map(main_func, group.groups.keys()) ... pool = Pool(processes=5) pool.map(main_func, [i for i in data.id.unique() if i in group.groups.keys()]) More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 1
3

You are splitting b1 on single spaces, and this can lead to empty values:

>>> '88  89 '.split(' ')
['88', '', '89', '']

It is the extra empty strings here that cause int() to throw an exception:

>>> int('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

Use str.split() with no argument instead; extra whitespace is then stripped:

>>> '88  89 '.split()
['88', '89']

You have some other problems as well in your code. Take a good look at:

def lab8():
    userinput= "Lab8.txt"
    lenoffile= len(userinput)
    print "There is", lenoffile, "lines"
    File= open (userinput, "r")
    studentscores1= File.read()
    studentlist= studentscores1.split("\n")
    return studentlist, lenoffile

Here, lenoffile is not the number of lines in the file. It is the number of characters in 'Lab8.txt'; both values happen to be 8, but add or remove some lines from that file and the number will be wrong for the rest of your code.

If you are supposed to keep these numbers together with the names and write out the calculations again, you'll have to do some work keeping the names together.

Here is an alternative version to solve the same task:

outputfile = raw_input("What is the output filename? :")

with open('Lab8.txt') as infile, open(outputfile, 'w') as outtfile:
    for name in infile:
        scores = next(infile).split()  # next() grabs the next line from infile here
        scores = map(int, scores)

        quiztotal = sum(scores[:4]) / 5
        midtermtotal = sum(scores[5:7]) / 2
        finaltotal = scores[7]
        score = quiztotal * .3 + midtermtotal * .4 + finaltotal * .3

        outfile.write(name)
        outfile.write('{0:0.2f}\n'.format(score))
🌐
Teclado
teclado.com › 30-days-of-python › python-30-day-20-map-filter
Day 20: map, filter, and Conditional Comprehensions | Teclado
numbers = [1, 56, 3, 5, 24, 19, 88, 37] even_numbers = {number for number in numbers if number % 2 == 0} We can also still perform modifications to the values as part of creating the new collection. The filtering condition is an augmentation of the usual comprehension syntax, and it doesn't limit anything we can normally do. Much like map is a functional analogue for "normal" comprehensions, filter performs the same role as a conditional comprehension.
🌐
HackerEarth
hackerearth.com › practice › notes › python-diaries-chapter-3
Python Diaries Chapter 3 Map | Filter | For-else | List Comprehension - Divyanshu Bansal
... We can also use list comprehension ... etc..) and returns a list of the results. Syntax of map function -> map(function, iterable[,optional args])...
🌐
YouTube
youtube.com › code cube
Using conditions with Map - Python - YouTube
How to use conditions for map and lambda in Python. if - else condition should be used for mapping the elements of list.
Published: November 15, 2019
Views: 198
Find elsewhere
🌐
Rafatieppo
rafatieppo.github.io › post › 2021_12_02_python_map_loop
Conditional in Python: map vs loop · Rafael Tieppo
December 2, 2021 - # loop start_time = time.time() ls_desc = [] for idx in range(len(df_prob)): if df_prob['day'].iloc[idx] <= 10: dd = '01' elif df_prob['day'].iloc[idx] > 10 and \ df_prob['day'].iloc[idx] <= 20: dd = '02' elif df_prob['day'].iloc[idx] > 20 and \ df_prob['day'].iloc[idx] <= 31: dd = '03' else: dd = '-99' ls_desc.append(dd) print("loop --- %s seconds ---" % (time.time() - start_time)) # map start_time = time.time() ls_desc = list(map(lambda x: '01' if x <= 10 else ('02' if x > 10 and x <= 20 else( '03' if x > 20 and x <= 31 else '-99')), df_prob['day'].values)) print("map --- %s seconds ---" % (time.time() - start_time)) ... The function map was better than loop.
🌐
Stack Overflow
stackoverflow.com › questions › 72749617 › lambda-function-within-map-function-with-if-but-without-else-statement-in-python
lambda function within map function with if but without else statement in Python - Stack Overflow
June 24, 2022 - By default functions return None, but I'm also using map function in the very beginning so instead of passing else statement it adds None in the collection. def inRangeFilter(lst): return list(map(lambda tpl: list(filter(lambda x: x in range(tpl[0], tpl[1] + 1), tpl[2])) if tpl[2] == list(filter(lambda x: x in range(tpl[0], tpl[1] + 1), tpl[2])) else None, lst)) print(inRangeFilter([(1, 5, [2, 3, 4]), (2, 12, [1, 2, 3, 10]), (3, 4, [])]))
🌐
Medium
medium.com › @ashdeepupadhyay › using-map-instead-of-if-else-or-switch-cb79de33b02b
Using map instead of if/else or switch | by ashdeep upadhyay | Medium
January 22, 2023 - Also the functions in the map should have same intention or the abstract for example if we are having a map for Authorization then it should not have some function with some other abstract such as calling, it’s not a good practise.
🌐
Real Python
realpython.com › lessons › mapping-conditions-handler-functions
Mapping Conditions to Handler Functions (Video) – Real Python
Join us and get access to thousands of tutorials and a community of expert Pythonistas. ... This lesson will show you how to use a dictionary to map conditions to handler functions. Here’s a code snippet from the lesson that shows how to create a dictionary mapping as well as how to call a function based on a condition: ... You’ll also learn that dictionaries can be a lot faster than using if statements because of the way they look up keys.
Published: March 2, 2019
🌐
LearnDataSci
learndatasci.com › solutions › python-map
Python map(function, iterable, ...) – LearnDataSci
In the previous section, we called map() with the built-in len, but we can also create our own functions. In the following code block, we created a function that calculates the factorial of a number, n. def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1)
🌐
W3Schools
w3schools.com › python › ref_func_map.asp
Python map() Function
The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter. ... def myfunc(a, b): return a + b x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon', 'pineapple')) ...
🌐
Python Morsels
pythonmorsels.com › map-and-filter-python
Python's map and filter functions - Python Morsels
August 3, 2026 - There's a little bit more to the ... cases map is essentially the same as a generator expression that loops over an iterable and calls a function on every item in that iterable (to transform each item). The filter function is essentially the same as this generator expression: def filter(function, iterable): return (x for x in iterable if function(x)) This generator expression loops over an iterable and calls a function on each item in the conditional part of the ...