Python 将单项列表转换为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15887885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting a one-item list to an integer
提问by Scott
I've been asked to accept a list of integers (x), add the first value and the last value in the list, and then return an integer with the sum. I've used the following code to do that, but the problem I have is that when I try to evaluate the sum it's actually a one-item list instead of an integer. I've tried to cast it to an int but I can't seem to get it to work.
我被要求接受一个整数列表 (x),将列表中的第一个值和最后一个值相加,然后返回一个带有总和的整数。我已经使用以下代码来做到这一点,但我遇到的问题是,当我尝试计算总和时,它实际上是一个单项列表而不是整数。我试图将它转换为 int 但我似乎无法让它工作。
def addFirstAndLast(x):
lengthOfList = len(x)
firstDigit = x[0:1]
lastDigit = x[lengthOfList:lengthOfList-1]
sum = firstDigit + lastDigit
return sum
采纳答案by Thomas Orozco
Use indexes
使用索引
You're slicing the list, which return lists. Here, you should use indexes instead:
您正在切片列表,它返回列表。在这里,您应该改用索引:
firstDigit = x[0]
lastDigit = x[-1]
Why is slicing wrong for you:
为什么切片对你来说是错误的:
When you do x[0:1], you're taking the list of itemsfrom the beginning of the list to the first interval.
当您这样做时x[0:1],您将获取从列表开头到第一个间隔的项目列表。
item0, item1, item2, item3
^ interval 0
^ interval 1
^ interval 2
^ interval 3
Doing x[0:2], for example, would return items 0 and 1.
这样做x[0:2],例如,将返回的项目0和1。
回答by óscar López
It all boils down to this:
这一切都归结为:
def addFirstAndLast(x):
return x[0] + x[-1]
In Python, a negative list index means: start indexing from the right of the list in direction to the left, where the first position from right-to-left is -1, the second position is -2and the last position is -len(lst).
在 Python 中,否定列表索引的意思是:从列表的右侧开始向左进行索引,从右到左的第一个位置是-1,第二个位置是-2,最后一个位置是-len(lst)。
回答by herinkc
Use Slice Notation:
使用切片符号:
def addFirstAndLast(x):
return x[0] + x[-1]
x[0]= will give you 0thindex of the list, first value.
x[0]= 会给你列表的第0个索引,第一个值。
x[-1]= will give you the lastelement of the list.
x[-1]= 会给你列表的最后一个元素。
回答by John
I'm just adding a special case here for anyone who is struggling like I was with list comprehensions, which return a list. @Thomas Orozco's answer saved me. This is a dead-simple example:
我只是在这里为任何像我一样在列表理解中挣扎的人添加一个特殊案例,它返回一个列表。@Thomas Orozco 的回答救了我。这是一个非常简单的例子:
mylist=[1,5,6]
[el for el in mylist if el==5]
>> [5] #returns a *list* containing the element -- not what I wanted
Adding a subscript extracts the element from the list.
添加下标将从列表中提取元素。
[el for el in mylist if el==5][0]
>> 5 #returns the element itself
If you want multiple elements returned as a tuple (not a list), you can enclose the whole statement:tuple([el for el in l if (el==5 or el==6)])
如果您希望将多个元素作为元组(而不是列表)返回,则可以将整个语句括起来:tuple([el for el in l if (el==5 or el==6)])

