简体   繁体   English

我的函数返回一个包含单个整数的列表,如何让它只返回整数?

[英]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]

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, ie: 我还建议让day_list成为函数的参数,即:

>>> 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: 并且为了使整个事物更有效( list.index是O(n))使用字典:

>>> 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

Return the first item, not the list: 返回第一个项目,而不是列表:

return [day for day in range(len(day_list)) if day_list[day] == inp][0]

But what you really want to do, is change your logic: 但你真正想做的是改变你的逻辑:

return day_list.index(inp)

Try this: 尝试这个:

return [day for day in range(len(day_list)) if day_list[day] == inp][0]

However, this is not the most efficient way to achieve this. 但是,这不是实现这一目标的最有效方法。 Try this instead: 试试这个:

day_list.index(inp)

I know it looks like I copied the other answer, I swear I didn't :) 我知道它看起来像我复制了另一个答案,我发誓我没有:)

This is a good use case for a dictionary: 这是字典的一个很好的用例:

>>> day_map = {day: index for index, day in enumerate(day_list)}

Use: 采用:

>>> day_map['Sunday']
0
>>> day_map['Tuesday']
2

You could also use the calendar module, which has constants defined for the weekdays (in English): 您还可以使用calendar模块,该模块具有为工作日定义的常量(英文):

>>> import calendar
>>> def day_to_number(day):
...     return getattr(calendar, day.upper())
... 
>>> day_to_number('wednesday') 
2 # Note that 0 = 'Monday'

If you are using this, you should probably add some error handling: 如果您正在使用它,您应该添加一些错误处理:

>>> day_to_number('epoch')
1970

Or: 要么:

>>> day_to_number('foo')
Traceback (most recent call last):
  File "<ipython-input-22-4649e99206ae>", line 1, in <module>
    day_to_number('foo')
  File "<ipython-input-14-bf0518eb14b5>", line 2, in day_to_number
    return getattr(calendar, day.upper())
AttributeError: 'module' object has no attribute 'FOO'

This looks overly complicated. 这看起来过于复杂。 You don't need a list comprehension for this task. 您不需要列表理解此任务。 You can use the index() method: 您可以使用index()方法:

>>> def day_to_number(inp):
...     return day_list.index(inp)
...
>>> day_to_number("Sunday")
0
>>> day_to_number("Monday")
1
>>> day_to_number("Saturday")
6

If you pass an invalid value, it will raise a ValueError 如果传递的值无效,则会引发ValueError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM