Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My function returns a list with a single integer in it, how can I make it return only the integer?

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]
like image 734
notMarc Avatar asked Feb 22 '16 15:02

notMarc


People also ask

How do I turn a list into an integer?

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.

How do you convert one integer to a list in Python?

Method 1: Use List Comprehension. Method 2: Use List and map() Method 3: Use List Comprehension and List. Method 4: Use a for Loop.

How do you create a function that returns a list?

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.

How do you convert a list to a number in Python?

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.


1 Answers

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
like image 50
timgeb Avatar answered Oct 14 '22 01:10

timgeb