繁体   English   中英

如何检查列表中的特定数字,然后计算特定元素直到该数字?

[英]How to check specific numbers in list and then count specific elements till that number?

我有一个任务来制作一个程序,该程序生成一个包含从 -10 到 10 的随机 50+ 数字的列表。然后我需要找到第一个负数并计算该数字之前从 1 到 5 的所有元素。

例如对于[2, 6, -1]结果应该是1

我确实需要在此任务中使用*args

我已经完成了几乎所有的代码,但我不知道如何从第一个负数返回并开始计数。

import random

def check(arr, val):  #creating function which is checking numbers      
    for x in arr:
      if val>= x: 
        return True 
    return False

def function(*args):
  val = 0
  if(check(arr, val)): 
    count = arr.count(1)
    count1 = arr.count(2)
    count2 = arr.count(3)
    count3 = arr.count(4)
    count4 = arr.count(5)
    print(count + count1 + count2 + count3 + count4)
  else: # how to start counting back from here?
    return print('No negative numbers')


def generate(x):
    array = []
for i in range(0, 50):
    array.append(random.randint(-10, 10))
return array

arr = generate(60)

print(arr)

function(*arr)
import random

def function(arr):
    counter = 0
    for el in arr:
        if el >= 0:
            counter += 1
        else:
            break
    return counter


def generate():
    array = []
    for i in range(50):
        array.append(random.randint(-10, 10))
    return array

my_arr = generate()

print(my_arr)

print(function(my_arr))

其他答案可能对您更有用。 这是一个更实用的方法。

首先,我使用列表理解来制作 50 个随机数的列表。 然后我只选择正数,但不包括第一个负数。 我将15之间的每个数字转换为True ,将其他所有数字转换为False 最后,我计算15之间有多少个数字,并将其打印到控制台。

from random import randint
from itertools import takewhile

numbers = [randint(-10, 10) for _ in range(50)]

print(sum(# accumluate the result and print
    map(# only count numbers that are between 1 and 5 inclusive
        lambda n: n in range(1, 6),
        takewhile( # get all numbers up to but not including negative numbers
            lambda n: n >= 0,
            numbers))))
from random import randint

#make a list of random numbers (integers)
numbers = [ randint(-10, 10) for i in range( 50 )]

#collect the only the negative number (ri) and their position (i)
negative_numbers = [ (i, ri) for i, ri in enumerate( numbers ) if ri < 0 ]
print( numbers )

#check to ensure there are negative numbers
if negative_numbers:
    #since i is the first position of that a negative occurs, 
    # count the numbers in the list between 1 and 5
    i, ri = negative_numbers[0] 
    
    n_preceding = len( [ri for ri in numbers[0:i] if ri >= 1 and ri <= 5 ] )
    
    print( f"first random number: {ri}" )
    print( f"numbers preceding: {n_preceding}")
else:
    print( f"no negative numbers were produced" )

上面的代码使用了列表迭代,在我看来这是 Python 的一个非常酷的特性。

numlist = [ i for i in range( 10 ) ]
#output: [ 0, 1, 2, 3, 4, 5.....]

strlist = [ si for si in "HELLO WORLD" ]
#output: [ "H", "E", "L", "L", "O".....]

filtered_list = [ si for si in "HELLO WORLD" if not si == "L" ]
#output = [ "H", "E", "O", " ", "W", "O", "R", "D" ]

#the for loop equivalent of the last
filtered_list = []
for si in "HELLO WORLD":
    if not si == "L":
        filtered_list.append( si )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM