简体   繁体   English

如何迭代两个不同长度的字典?

[英]How to iterate over two dictionaries of different lengths?

This is a problem from Codewars - but basically I am trying to iterate through two different dictionaries of different lengths.这是 Codewars 的一个问题 - 但基本上我试图遍历两个不同长度的不同词典。 I can't use zip() because I know any trailing items without a pair will be ignored.我不能使用zip()因为我知道任何没有成对的尾随项目都将被忽略。

Let's say s1 = "aaaa bb c" and s2 = "aaa bbb c dd" Output should only reflect letters from the string that have the greater frequency (anything with a letter freq of 1 will be ignored) here's the link to the question: https://www.codewars.com/kata/5629db57620258aa9d000014假设s1 = "aaaa bb c"s2 = "aaa bbb c dd"输出应该只反映字符串中频率更高的字母(任何字母频率为 1 的都将被忽略)这里是问题的链接: https://www.codewars.com/kata/5629db57620258aa9d000014

My code as it stands doesn't have the slashes in yet (I'll add that after) and because I'm only iterating over one dictionary, it leaves off the d outputs from the second dictionary.我的代码目前还没有斜线(我会在后面添加)并且因为我只迭代一个字典,所以它忽略了第二个字典的d输出。

def mix(s1,s2):

    d1 = {i:s1.count(i) for i in s1 if i.islower()}
    print(d1)

    d2 = {j:s2.count(j) for j in s2 if j.islower()}
    print(d2)

    res = ""
    for k in d1:
        if d1[k] <=1 or d2[k] <=1:
            pass 
        elif d1[k] > d2[k]:
            res += "1:" + k * d1[k]
        elif (d1[k] < d2[k]):
            res += "2:" + k * d2[k]
        elif d1[k] == d2[k]:
            res += "=:" + k*d1[k]
        elif k not in d2:
            res += "1:" + k*d1[k]
        else:
            res += "2:" + k*d1[k]

    return res

Output should be: "1:aaaa/2:bbb/2:dd"输出应为: "1:aaaa/2:bbb/2:dd"

# your input
s1 = "aaaa bb c"
s2 = "aaa bbb c dd"

#use Python Counter from collections (as the name suggests it counts and makes a dictionary)
from collections import Counter
c1 = Counter(s1)
c2 = Counter(s2)
print(c1, '\n', c2)

# my custom key for sorting the keys
def my_custom_key (inp):
    ret = 0
    if inp in c1: ret = max(ret, c1[inp])
    if inp in c2: ret = max(ret, c2[inp])
    return ret

my_answer = list(set(list(c1.keys())+list(c2.keys())))
#my_answer = c1.keys() | c2.keys() #shorter form of above line of code
my_answer = sorted(my_answer, key = my_custom_key, reverse=True)
print(my_answer)

#doing the last check like max freq is > 1 and it is lower case english alphabet
my_str_answer = []
for i in my_answer:
    #check if lowercase alphabet
    if ord(i)<ord('a') or ord(i)>ord('z')or my_custom_key (i)<2: continue
    curr_str = f"{abs(c1[i]-c2[i])}:{i*my_custom_key (i)}"
    my_str_answer.append(curr_str)
my_str_answer = "/".join(my_str_answer)
print(my_str_answer)
Counter({'a': 4, ' ': 2, 'b': 2, 'c': 1}) 
 Counter({'a': 3, ' ': 3, 'b': 3, 'd': 2, 'c': 1})
['a', 'b', ' ', 'd', 'c']
1:aaaa/1:bbb/2:dd
from collections import Counter

def filter_chars(s):
        return dict(sorted(filter(lambda k: k[0].islower() and k[1] > 1, Counter(s).items()), key=lambda k: -1 * k[1]))

def mix_chars(d1, d2, seed={}, inverted=False):
    for k, v in d1.items():
        v2 = d2.get(k, 0)
        val = (v, '2' if inverted else '1')
        if v == v2:
            val = (v, '=') 
        elif v > v2:
            val = (v, '2' if inverted else '1')
        else:
            val = (v2, '1' if inverted else '2')             
        seed[k] = val
        d2.pop(k, None)
    return seed
    
def string_mix(s1, s2):
    d1 = filter_chars(s1)
    d2 = filter_chars(s2)
    seed = {}
    seed = mix_chars(d1, d2, seed)
    seed = mix_chars(d2, d1, seed, True)
    return '/'.join(map(lambda k: k[1][1] + ':' + k[0] * k[1][0], sorted(seed.items(), key=lambda i: -1 * i[1][0])))

s1 = "mmmmm m nnnnn y&friend&Paul has heavy hats! &"
s2 = "my frie n d Joh n has ma n y ma n y frie n ds n&"
print(string_mix(s1, s2))

s1 = "aaaa bb c"
s2 = "aaa bbb c dd"
print(string_mix(s1, s2))

Here is the output这是输出

1:mmmmmm/=:nnnnnn/1:aaaa/1:hhh/2:yyy/=:ee/=:ss/2:ff/2:rr/2:ii/2:dd 1:mmmmmm/=:nnnnnn/1:aaaa/1:hhh/2:yyy/=:ee/=:ss/2:ff/2:rr/2:ii/2:dd

1:aaaa/2:bbb/2:dd 1:aaaa/2:bbb/2:dd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM