【问题标题】:Python prints string as list of charactersPython将字符串打印为字符列表
【发布时间】:2020-07-01 07:31:24
【问题描述】:
def make_word_list(file_object):
    return [line.strip() for line in file_object]

def is_anagram(s1, s2):
    return sorted(s1) == sorted(s2)

def find_anagrams(word_list):
    anagram_dict = {}
    for word in word_list:
        k = str(sorted(word))
        anagram_dict[k] = anagram_dict.get(k, []) + [word]

    for k, v in sorted(anagram_dict.items()):
        if len(v) > 1:
            print(str(k), str(v))

if __name__ == '__main__':
    fin = open('words.txt')
    word_list = make_word_list(fin)
    find_anagrams(word_list)

当我运行这个程序时,它会一直打印字符串(“k”)作为字符串列表。我检查了类型,它确认它是一个字符串。请帮忙。

【问题讨论】:

  • k = str(sorted(word)) sorted 返回一个列表。 k 包含列表的字符串表示形式。
  • 使用"".join(sorted(word)) 将列表重新组合成一个字符串。

标签: python string list loops for-loop


【解决方案1】:

str 返回你给它的字符串表示形式。在列表中,它会将项目打印为列表。

相反,您需要使用

将字符重新连接成字符串
"".join(sorted(word))

"".join(list) 将列表中的所有元素加在一起,用引号中的内容分隔。好像你在写

lst= [1,2,3]
result = []
separator = ","
for i in list:
     result = result + "," + i
result = result[len(separator):] # Remove the first separator

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多