python 我试图从头开始构建一个unique()函数,但看起来for循环在第一个循环之后没有迭代

ws51t4hk  于 2023-10-15  发布在  Python
关注(0)|答案(3)|浏览(92)

我试图从头开始构建一个unique()函数,但看起来for循环在第一个循环之后没有迭代

def uni(x):
    s = set(l)
    count = 0
    for i in s:
        for j in x:
            if i == j:
                count += 1
        return f"{i}: {count}"


l = ["business", "business", "business", "economy", "economy", "economy", "economy", "business", "premium", "business", "first"]
xx = uni(l)
print(xx)

我希望输出像商业:5经济:4第一:1溢价:1

h4cxqtbf

h4cxqtbf1#

您将return语句放在for循环中,这就是它在第一次迭代后退出的原因

def uni(x):
    s = set(l)
    count = {}
    for i in s:
        for j in x:
            if i == j:
                count += 1
    return f"{i}: {count}"

l = [“business”,“business”,“business”,“economy”,“economy”,“economy”,“economy”,“business”,“premium”,“business”,“first”] xx = uni(l)print(xx)
试试这个,希望有帮助

acruukt9

acruukt92#

有很多事情要指出。所以,最小修改的版本应该是这样的:

def uni(str_array):
    s = set(str_array)
    result = ""
    for i in s:
        count = 0
        for j in str_array:
            if i == j:
                count += 1
        result = result + i + ':' + str(count) + ' '
    return result

或者,如果你可以使用dict,像这样:

def uni(str_array):
    s = set(str_array)
    result = {}
    for i in s:
        count = 0
        for j in str_array:
            if i == j:
                count += 1
        result[i] = count
    return result
zpgglvta

zpgglvta3#

如果你真的想从头开始构建它(而不是使用 collections 模块中的Counter类),那么:

L = ["business", "business", "business", "economy", "economy", "economy", "economy", "business", "premium", "business", "first"]

def unique(lst):
    d = {}
    for e in lst:
        d[e] = d.get(e, 0) + 1
    return [f'{k}:{v}' for k, v in d.items()]

print(*unique(L))

输出:

business:5 economy:4 premium:1 first:1

相关问题