函数返回值的长度

时间:2019-02-18 21:53:53

标签: python python-3.x function

我有一个小程序,可以接受一个或多个列表,将内容随机化,然后打印出来。

import random


def randomize(*seq):
    shuffled = list(seq)
    for i in shuffled:
        random.shuffle(i)
    return iter(shuffled)


colors = ["red", "blue", "green", "purple"]
shapes = ["square", "circle", "triangle", "octagon"]

for i in randomize(colors, shapes):
    print(i)

它按原样工作。

我还希望能够在返回值上获得len()。

  • 如果我做len(randomize(colors)),我应该回去4
  • 如果我做len(randomize(colors, shapes)),我应该回去8

我收到此错误:Expected type 'Sized', got 'Iterator' instead

正在研究len()__len__,但我不确定如何解决这个问题。

2 个答案:

答案 0 :(得分:0)

从返回中丢弃def randomize(*seq): shuffled = list(seq) for i in shuffled: random.shuffle(i) return shuffled colors = ["red", "blue", "green", "purple"] shapes = ["square", "circle", "triangle", "octagon"] randomized = randomize(colors, shapes) print('number of lists', len(randomized)) print('total number of elements', sum([len(l) for l in randomized])) for i in randomized: print(i) 呼叫。没有它,循环将起作用。

randomize

为避免汇总返回的列表,您需要更改{{1}}的返回值,这取决于结果。最简单的更改是将列表在混排后进行串联。

答案 1 :(得分:0)

我认为您想要这样的东西-它会串联您的列表,然后将它们洗牌

import random
import itertools

def randomize(*seq):
    shuffled = list(itertools.chain.from_iterable(seq))
    random.shuffle(shuffled)
    return iter(shuffled)


colors = ["red", "blue", "green", "purple"]
shapes = ["square", "circle", "triangle", "octagon"]

res = list(randomize(colors, shapes))
for i in res:
    print(i)

print('length: {}'.format(len(res)))

如果您不希望这样做,也可以:

import random
import itertools

def randomize(*seq):
    shuffled = list(seq)
    for i in shuffled:
        random.shuffle(i)
    return iter(shuffled)


colors = ["red", "blue", "green", "purple"]
shapes = ["square", "circle", "triangle", "octagon"]

length = len(list(itertools.chain.from_iterable( randomize(colors, shapes))))
print('length: {}'.format(length))

for i in randomize(colors, shapes):
    print(i)