简体   繁体   English

如何从词典中输出值而不将其打印为列表?

[英]How to output values from a dictionary without printing it out as a list?

I was a assigned to group ana grams together lexiographicaly. 我被分配来按书法将anag分组在一起。

Below is one of the test cases: 以下是测试案例之一:

Input: eat tea tan ate nat bat 输入: eat tea tan ate nat bat

Output: 输出:

ate eat tea bat nat tan

However, I keep getting the following output where the the anagrams are encapsulated in the list and the order at which each line gets printed varies every time: 但是,我不断得到以下输出,其中将字谜封装在列表中,并且每行的打印顺序每次都不同:

['ate', 'eat', 'tea'] ['nat', 'tan'] ['bat'] or ['ate', 'eat', 'tea'] ['nat', 'tan'] ['bat']

['nat', 'tan'] ['bat'] ['ate', 'eat', 'tea'] or ['nat', 'tan'] ['bat'] ['ate', 'eat', 'tea']

['ate', 'eat', 'tea'] ['bat'] ['nat', 'tan']

How do I fix this so that it outputs without being capped in a list and possibly in the right order? 如何解决此问题,使其输出而不会在列表中加盖,也可能以正确的顺序加盖?

This is what i have done so far: 这是我到目前为止所做的:

import sys
from collections import *
def ComputeAnagrams(string):
    d = defaultdict(list)
    for word in string:
        key = ''.join(sorted(word))
        d[key].append(word)
    return d

def main():
    for string in sys.stdin:
        stringList = string.split()
        if len(stringList) == 0:
            break
        d = ComputeAnagrams(stringList)
        for key,anagrams in d.items():
            if len(anagrams) >=1:
                print(sorted(anagrams))
        print ('')
main()

Note: the machine that runs this programs reads input from stdin/keyboard and prints the output to console(stdout). 注意:运行该程序的计算机从stdin / keyboard读取输入,并将输出打印到console(stdout)。

I believe the issue is - 我相信问题是-

print(sorted(''.join(anagrams)))

You are using sorted after join the list to a string, in that case, sorted returns a list of characters in the sorted order (I guess that is the current output you are getting). 将列表连接到字符串后,您将使用sorted ,在这种情况下,sorted将按排序顺序返回一个字符列表(我想这是您得到的当前输出)。

If you want the elements in sorted order, sorted should be used on anagrams list, not the string after joining. 如果要按排序顺序排列元素,则应在anagrams列表上使用sorted,而不要在加入后使用字符串。 Example - 范例-

print(', '.join(sorted(anagrams)))

I am also using ', ' to join the strings, so as to use , as the separator, otherwise the output would be all strings together without any spaces in-between, if you want, you can use any other separator you want. 我还使用', '来连接字符串,以便使用,作为分隔符,否则输出将所有字符串都在一起,而中间没有任何空格,如果需要,可以使用任何其他分隔符。

Demo - 演示-

After above change - 经过以上更改-

Input - 输入-

eat tea tan ate nat bat

Output - 输出-

bat
ate, eat, tea
nat, tan

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

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