创建两个包含 10 个实例的列表,然后创建第三个包含 x 和 y 10 次的列表

问题描述 投票:0回答:3

有人向我提出问题,但我不太明白他们要我做什么。他们给我的问题是:

本练习的目标是创建两个名为

x_list
y_list
的列表,其中分别包含变量
x
y
的 10 个实例。您还需要通过连接您创建的两个列表来创建一个名为
big_list
的列表,其中包含变量
x
y
,各 10 次。

随之而来的代码是:

x = object()
y = object()

# change this code
x_list = [x]
y_list = [y]
big_list = x_list + y_list

print "x_list contains %d objects" % len(x_list)
print "y_list contains %d objects" % len(y_list)
print "big_list contains %d objects" % len(big_list)

# testing code
if x_list.count(x) == 10 and y_list.count(y) == 10:
    print "Almost there..."
if big_list.count(x) == 10 and big_list.count(y) == 10:
    print "Great!"

结果是:

x_list contains 10 objects
y_list contains 10 objects
big_list contains 20 objects

Almost there...
Great!
python list variables
3个回答
5
投票

要获取多个实例,只需将列表相乘即可:

x_list = [x]*10
y_list = [y]*10

0
投票
x = object()
y = object()

# TODO: change this code
x_list = [x]*10
y_list = [y]*10
big_list = []

z = x_list + y_list
big_list.append(z)


print("x_list contains %d objects" % len(x_list))
print("y_list contains %d objects" % len(y_list))
print("big_list contains %d objects" % len(big_list))

# testing code
if x_list.count(x) == 10 and y_list.count(y) == 10:
    print("Almost there...")
if big_list.count(x) == 10 and big_list.count(y) == 10:
    print("Great!")

0
投票

要制作 10 个实例,我们只需将其与

10
相乘,然后在
x_list
中添加
y_list
big_list

代码:

x = object()
y = object()

# TODO: change this code
x_list = [x]*10
y_list = [y]*10
big_list = x_list + y_list

print("x_list contains %d objects" % len(x_list))
print("y_list contains %d objects" % len(y_list))
print("big_list contains %d objects" % len(big_list))

# testing code
if x_list.count(x) == 10 and y_list.count(y) == 10:
    print("Almost there...")
if big_list.count(x) == 10 and big_list.count(y) == 10:
    print("Great!")

输出:

x_list contains 10 objects
y_list contains 10 objects
big_list contains 20 objects
Almost there...
Great!
© www.soinside.com 2019 - 2024. All rights reserved.