[英]How to create a list that results a number from a given list, not the indices?
我在獲取結果以生成列表中的整數時遇到麻煩,而不是它屬於哪個索引。
#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]
您正在遍歷索引范圍。 而是遍歷列表。
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]
列表推導極大地簡化了您的代碼。
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]
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
情況oddList
如此。
注意:@Sukrit Kalra的解決方案是更可取的,但我在此保留它,以表明有多種解決方法。
仔細看看.append()命令...在比較中,您正在使用:
if ((mylList[i])%2!=0)
要么
if ((myList[i])>5)
...但是當您將其放入列表中時,您只是在使用
greaterList.append(i)
代替
greaterList.append(myList[i])
這一定是家庭作業或某個地方的課程嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.