我无法获得结果以在列表中生成整数,而不是它所属的索引。
#this function takes, as input, a list of numbers and an option, which is either 0 or 1.
#if the option is 0, it returns a list of all the numbers greater than 5 in the list
#if the option is 1, it returns a list of all the odd numbers in the list
def splitList(myList, option):
#empty list for both possible options
oddList = []
greaterList = []
#if option is 0, use this for loop
if int(option) == 0:
#create for loop the length of myList
for i in range(0, len(myList)):
#check if index is greater than 5
if ((myList[i])>5):
#if the number is greater than 5, add to greaterList
greaterList.append(i)
#return results
return greaterList
#if option is 1, use this for loop
if int(option) == 1:
#create for loop the length of myList
for i in range(0, len(myList)):
#check if index is odd by checking if it is divisible by 2
if ((myList[i])%2!=0):
#if index is not divisible by 2, add the oddList
oddList.append(i)
#return results
return oddList
我收到的结果如下:
>>>splitList([1,2,6,4,5,8,43,5,7,2], 1)
[0, 4, 6, 7, 8]
我想把结果变成[1,5,43,5,7]
答案 0 :(得分:2)
您正在迭代索引的范围。相反,迭代列表。
for i in myList:
#check if index is greater than 5
if i >5:
#if the number is greater than 5, add to greaterList
greaterList.append(i)
因此,您的代码会被重写为(稍作修改)
def splitList(myList, option):
final_list = []
if int(option) == 0:
for i in myList:
if i > 5:
final_list.append(i)
elif int(option) == 1:
for i in myList:
if i%2 != 0:
final_list.append(i)
return final_list
您可以通过
来减少它def splitList(myList, option):
if int(option) == 0:
return [elem for elem in myList if elem > 5]
elif int(option) == 1:
return [elem for elem in myList if elem % 2 != 0]
输出 -
>>> splitList([1,2,6,4,5,8,43,5,7,2], 1)
[1, 5, 43, 5, 7]
答案 1 :(得分:2)
列表推导大大简化了您的代码。
def split_list(xs, option):
if option:
return [x for x in xs if x % 2]
else:
return [x for x in xs if x > 5]
答案 2 :(得分:1)
if ((myList[i])>5):
#if the number is greater than 5, add to greaterList
greaterList.append(i)
不添加索引i
,而是添加值(myList[i]
):
if ((myList[i])>5):
#if the number is greater than 5, add to greaterList
greaterList.append(myList[i])
oddList
案例也是如此。
注意:@Sukrit Kalra的解决方案更可取,但我要离开这一点,以表明有多种解决方法。
答案 3 :(得分:0)
在你正在使用的比较中仔细查看你的.append()命令......
if ((mylList[i])%2!=0)
或
if ((myList[i])>5)
...但是当你把它放到列表中时,你只是使用
greaterList.append(i)
而不是
greaterList.append(myList[i])
这必须是某个地方的家庭作业或课堂吗?