[英]Python function that returns values from list smaller than a number
我的函數需要接受整數列表和某個整數,並返回列表中小於特定整數的數字。 有什么建議?
def smallerThanN(intList,intN):
y=0
newlist=[]
list1=intList
for x in intList:
if int(x) < int(intN):
print(intN)
y+=1
newlist.append(x)
return newlist
使用帶有“if”過濾器的列表推導來提取列表中小於指定值的值:
def smaller_than(sequence, value):
return [item for item in sequence if item < value]
我建議為變量賦予更多通用名稱,因為無論序列的項目類型如何,此代碼都適用於任何序列(當然,前提是比較對於所討論的類型有效)。
>>> smaller_than([1,2,3,4,5,6,7,8], 5)
[1, 2, 3, 4]
>>> smaller_than('abcdefg', 'd')
['a', 'b', 'c']
>>> smaller_than(set([1.34, 33.12, 1.0, 11.72, 10]), 10)
[1.0, 1.34]
NB已經有類似的答案,但是,我更願意聲明一個函數而不是綁定一個lambda表達式。
integers_list = [4, 6, 1, 99, 45, 76, 12]
smallerThan = lambda x,y: [i for i in x if i<y]
print smallerThan(integers_list, 12)
輸出:
[4,6,1]
def smallerThanN(intList, intN):
return [x for x in intList if x < intN]
>>> smallerThanN([1, 4, 10, 2, 7], 5)
[1, 4, 2]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.