【问题标题】:Why am I not getting the correct number of objects in my list?为什么我的列表中没有正确数量的对象?
【发布时间】:2021-02-12 15:34:00
【问题描述】:

我正在尝试创建一个函数来生成元组列表。我有这个:

import random

def generate_list(count):
    l_names = ['scott', 'anderson', 'philips', 'peterson', 'parker']
    f_names = ['james', 'chris', 'lisa', 'mary', 'kate']
    names = []
    counter = 0

    for name in f_names:
        counter += 1
        my_tuple = (counter, f_names[random.randint(0, len(f_names)-1)], \
            l_names[random.randint(0, len(l_names)-1)])
        names.append(my_tuple) 
    return my_tuple

people = generate_list(3)
print(f"People list: {people}")

当我使用 generate_list(3) 时,我希望列表中有三个元组。但我只得到一个。我觉得错误出在 for 循环及其 return 语句中的某个地方。但我想不通。

谁能帮忙?

谢谢

【问题讨论】:

  • return names 而不是 return my_tuple?
  • 你没有使用count
  • 使用random.choice(f_names) 而不是f_names[random.randint(0, len(f_names)-1)]

标签: python function for-loop


【解决方案1】:

for name in f_names 更改为for name in range(count) 并将return mytuple 更改为return names,因为您返回的是一个元组而不是名称列表。

import random

def generate_list(count):
    l_names = ['scott', 'anderson', 'philips', 'peterson', 'parker']
    f_names = ['james', 'chris', 'lisa', 'mary', 'kate']
    names = []
    counter = 0

    for name in range(count):  #change f_names to count
        counter += 1
        my_tuple = (counter, random.choice(f_names), \
            random.choice(l_names))
        names.append(my_tuple) 
    return names #return names not my_tuples

people = generate_list(3)
print(f"People list: {people}")

【讨论】:

  • 啊! range(count) 是我将限制传递给函数的方式!我尝试将我的计数器更改为计数,但这是不行的。我尝试返回名称,然后我最终得到了整个列表。伙计,作为新手是艰难的。 :) 谢谢你,乔纳斯!感谢您的帮助。
【解决方案2】:
import random

def generate_list(count):
    l_names = ['scott', 'anderson', 'philips', 'peterson', 'parker']
    f_names = ['james', 'chris', 'lisa', 'mary', 'kate']
    names = []
    counter = 0

    while counter < count:
        counter += 1
        my_tuple = (counter, f_names[random.randint(0, len(f_names)-1)], \
            l_names[random.randint(0, len(l_names)-1)])
        names.append(my_tuple)
    return names

people = generate_list(3)
print(f"People list: {people}")

这个想法是正确的,但是您创建的 for 循环遍历了 f_names 的所有名称,这不是您要寻找的东西。因此,您可以将 for 循环更改为简单的 while 循环,以便在达到函数中给出的计数时停止。

【讨论】:

  • 嗨,乔迪,这也很好用。我知道我必须对伯爵做点什么,但不知道在哪里做。感谢您的帮助和花时间写解释。非常感谢。
猜你喜欢
  • 2011-05-18
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 2016-05-30
  • 1970-01-01
  • 2014-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多