【问题标题】:Reading strings from a file to find unique characters从文件中读取字符串以查找唯一字符
【发布时间】:2023-03-27 20:13:01
【问题描述】:

我正在尝试从字符串列表中查找具有最独特字母的单词。对我来说,问题是找不到字符串的唯一单词,因为我知道如何做到这一点,不,我的问题是在字符串列表中逐步查找每个单词的唯一字符。

示例:假设我的字符串列表是...

[苹果、香蕉、提基]

我希望列表看起来像

[Aple、Ban、Tik]

每当我尝试逐步完成时,我最终都会将整个列表粉碎在一起,而不是用逗号分隔,而我的所有其他解决方案都没有产生任何结果。我不能使用任何包或 set() 函数。

def unique_letters(words_list):

    count = 0 
    while(count < len(words_list)):
        for i in lines[count]:
        if i not in temp:
            temp.append(i)
            dupes = ''.join(temp) 
    count += 1
    return dupes

我最终得到的是......

'ApleBanTik' ### when I want ---> [Aple, Ban, Tik]

我一直在研究另一种解决方案,但最终得到了同样的结果。有什么建议可以解决吗?

【问题讨论】:

    标签: python string list file


    【解决方案1】:

    你可以这样做(使用列表理解):

    def unique_letters(words_list):
        return [''.join(dict.fromkeys(word)) for word in words_list]
    

    这是扩展版:

    def unique_letters(words_list):
        result = []
        for word in words_list:
            result.append(''.join(dict.fromkeys(word)))
        return result
    

    当您将单词转换为字典时,它会删除所有重复项。然后,我们只需将字典转换为字符串。

    【讨论】:

    • 我有一种感觉我应该尝试字典,这只能解决我的问题的一部分,因为我从原始问题中省略了另一半,但现在我有了这个我很确定我可以解决剩下的。非常感谢!
    • 糟糕,我找到你了。只是一个后续更新,我现在能够获得完整的功能。谢谢大家!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 2015-06-24
    • 2019-05-23
    相关资源
    最近更新 更多