簡體   English   中英

如何為列表創建 function 到 output 范圍(在 python 中)

[英]How to create a function to output ranges for a list (in python)

我需要創建一個 function 輸入整數列表並輸出三個范圍之一的計數。 知道有更簡單的方法可以做到這一點,但這是這個項目需要完成的方式。

假設范圍需要是: (x < 10, 10 <= x < 100, x >= 100)

到目前為止,我已經嘗試...

list = (1, 2, 10, 20, 50, 100, 200)
low = 0
mid = 0
high = 0
final_list = list()

def func(x):
    if x < 10:
        low = low + 1
    elif x < 100:
        mid = mid + 1
    else:
        high = high + 1

for i in range(len(list)):
    x  = func(list[i])
    final_list.append(x)

這是我能想到的最好的,但顯然它是不正確的。 同樣,我意識到有更簡單的方法可以完成此操作,但是針對此特定問題需要創建的 function 和 for 循環。

所以......有什么想法嗎?

你有兩個問題:

  • 您的 function 不返回任何內容
  • 您的累加器(計數)與您的循環分開

移動 function 內部的循環:

def func(values):

    low = 0
    mid = 0
    high = 0

    for x in values:

        if x < 10:
            low = low + 1
        elif x < 100:
            mid = mid + 1
        else:
            high = high + 1

    return low, mid, high


print(func([1, 2, 10, 20, 50, 100, 200]))

Output:

(2, 3, 2)

或另一種方式,具體取決於您需要將計數器用於:

my_list = (1, 2, 10, 20, 50, 100, 200)
# renamed the variable so it does not shadow the builtin list() type


def main():
    # created a function main() to allow the counters to be available to func() as nonlocal variables
    low = 0
    mid = 0
    high = 0
    final_list = list()

    def func(x):  # embedded func() in main()
        nonlocal low, mid, high  # declared the counters as nonlocal variables in func()
        if x < 10:
            low += 1
        elif x < 100:
            mid += 1
        else:
            high += 1

    for x in my_list:  # simplified the iteration over my_list
        func(x)
        final_list.append(x)  # final_list is just a copy of my_list - may not be necessary
    print(low, mid, high)  # to display the final values of the counters


main()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM