使用列表和切片语法查找数字列表中的最新值

时间:2016-04-27 15:10:56

标签: python list python-3.x syntax

我需要帮助完成这项任务。我只能做到下面的代码,我真的很难满足其他要求(下面)。

要求

  • 以无顺序列出名为nums的十个整数。 使用小于100的数字。

  • 使用循环显示列表,其中所有数字在同一行上以空格分隔。

  • 使用切片语法从nums中的中间六个数字创建一个名为nums2的新列表。

  • 将nums2作为名为list_func的void函数的唯一参数。

  • 在list_func函数内,显示切片中的最大数字及其索引。

示例输出为:

Here is the original list:
22 12 55 44 85 64 33 19 96 70 
Largest value in slice is 85
85 is at index 2 in the slice

脚本是:

import random

def main():

    nums =[]
    num2 = []

    for n in range (10):
        rando = random.randint(1,100)
        nums.append(rando)

    print('Here is the original list ')
    print(nums)


main()

我在nums2列表部分。

1 个答案:

答案 0 :(得分:1)

  
      
  • 使用切片语法从nums中的中间六个数字创建一个名为nums2的新列表。
  •   
MIDDLE_N = 6

n = (len(nums) - MIDDLE_N) // 2
nums2 = nums[n:][:MIDDLE_N]

print('Here is the middle 6 list ')
print(' '.join(str(n) for n in nums2))

nums[n:]从索引n开始创建新列表。 nums[n:][:MIDDLE_N]使用第一个nums[n:]元素从MIDDLE_N创建一个新列表。

  
      
  • 将nums2作为名为list_func的空函数的唯一参数。
  •   
  • 在list_func函数内,显示切片中的最大数字及其索引。
  •   
def list_func(l):
    top = max(l)
    print('Largest value in slice is {}'.format(top))
    print('{} is at index {} in the slice'.format(top, l.index(top)))

list_func(nums2)

全部放在一起

import random

def list_func(l):
    top = max(l)
    print('Largest value in slice is {}'.format(top))
    print('{} is at index {} in the slice'.format(top, l.index(top)))

def main():
    nums = []
    for n in range (10):
        rando = random.randint(1,100)
        nums.append(rando)

    print('Here is the original list ')
    # This is a kind of loop -- a generator expression.
    print(' '.join(str(n) for n in nums))

    MIDDLE_N = 6

    n = (len(nums) - MIDDLE_N) // 2
    nums2 = nums[n:][:MIDDLE_N]

    print('Here is the middle 6 list ')
    print(' '.join(str(n) for n in nums2))

    list_func(nums2)

main()

输出

Here is the original list 
49 82 16 68 47 8 30 41 24 34
Here is the middle 6 list 
16 68 47 8 30 41
Largest value in slice is 68
68 is at index 1 in the slice