【问题标题】:Python Iterating an ArrayPython迭代数组
【发布时间】:2020-03-29 21:51:09
【问题描述】:

我一直在尝试遍历一个数组。

下面是代码。

x = ['lemon', 'tea', 'water', ]

def randomShuffle (arr,n):
    from random import choices
    newList=[]


    for item in arr:
        r=choices(arr, k=n)

        if r.count(item) <= 2:
            newList.append(item)

        return (newList)

我想知道写它的逻辑。

谢谢大家

【问题讨论】:

    标签: arrays python-3.x random


    【解决方案1】:

    使用 while 循环:如果每个项目要出现两次,那么结果数组的长度应该是输入数组长度的两倍。
    当然,请检查不要在结果中添加相同的项目超过两次;)

    Choices 返回一个大小为 1 的列表,所以我使用 [0] 来获取元素

    xx = ["a", "b", "c"]
    
    def my_function(x):
        res = []
        while len(res) < len(x) * 2:
            c = choices(x)[0]
            if res.count(c) < 2:
                res.append(c)
        return res
    
    my_function(xx)
    > ['c', 'c', 'a', 'b', 'a', 'b']
    my_function(xx)
    > ['a', 'b', 'b', 'a', 'c', 'c']
    

    【讨论】:

    • 谢谢伙计。这正是我们所需要的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 2018-07-16
    • 2015-04-04
    • 2019-01-25
    相关资源
    最近更新 更多