How do I remove the brackets from the result while keeping the function a single line of code?
day_list = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
def day_to_number(inp):
return [day for day in range(len(day_list)) if day_list[day] == inp]
print day_to_number("Sunday")
print day_to_number("Monday")
print day_to_number("Tuesday")
print day_to_number("Wednesday")
print day_to_number("Thursday")
print day_to_number("Friday")
print day_to_number("Saturday")
Output:
[0]
[1]
[2]
[3]
[4]
[5]
[6]
This basic method to convert a list of strings to a list of integers uses three steps: Create an empty list with ints = [] . Iterate over each string element using a for loop such as for element in list . Convert the string to an integer using int(element) and append it to the new integer list using the list.
Method 1: Use List Comprehension. Method 2: Use List and map() Method 3: Use List Comprehension and List. Method 4: Use a for Loop.
Practical Data Science using Python Any object, even a list, can be returned by a Python function. Create the list object within the function body, assign it to a variable, and then use the keyword "return" to return the list to the function's caller.
Approach #3 : Using map() Another approach to convert a list of multiple integers into a single integer is to use map() function of Python with str function to convert the Integer list to string list. After this, join them on the empty string and then cast back to integer.
The list comprehension is overkill. If your list does not contain duplicates (as your sample data shows, just do)
>>> def day_to_number(inp):
... return day_list.index(inp)
...
>>> day_to_number("Sunday")
0
I would also advice to make the day_list
an argument of the function, i.e.:
>>> def day_to_number(inp, days):
... return days.index(inp)
...
>>> day_to_number("Sunday", day_list)
0
Looking it up in the global name space is a bit ugly.
And to make the whole thing more efficient (list.index
is O(n)) use a dictionary:
>>> days = dict(zip(day_list, range(len(day_list))))
>>> days
{'Monday': 1, 'Tuesday': 2, 'Friday': 5, 'Wednesday': 3, 'Thursday': 4, 'Sunday': 0, 'Saturday': 6}
>>>
>>> def day_to_number(inp, days):
... return days[inp]
...
>>> day_to_number("Sunday", days)
0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With