查找两个字符串之间的常见字符

编程入门 行业动态 更新时间:2024-10-24 16:24:30
本文介绍了查找两个字符串之间的常见字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用for循环从两个不同的用户输入中打印常用字母. (我需要使用for循环来完成此操作.)我遇到了两个问题:1.我的语句"If char not in output ..."没有提取唯一值. 2.输出为我提供了单个字母列表,而不是单个字符串.我尝试了分割输出,但是分割遇到了类型错误.

I am trying to print the common letters from two different user inputs using a for loop. (I need to do it using a for loop.) I am running into two problems: 1. My statement "If char not in output..." is not pulling unique values. 2. The output is giving me a list of individual letters rather than a single string. I tried the split the output but split ran into a type error.

wrd = 'one' sec_wrd = 'toe' def unique_letters(x): output =[] for char in x: if char not in output and char != " ": output.append(char) return output final_output = (unique_letters(wrd) + unique_letters(sec_wrd)) print(sorted(final_output))

推荐答案

您正在尝试执行设置交叉点. Python具有 set.intersection 方法相同.您可以按以下方式将其用于您的用例:

You are trying to perform the Set Intersection. Python has set.intersection method for the same. You can use it for your use-case as:

>>> word_1 = 'one' >>> word_2 = 'toe' # v join the intersection of `set`s to get back the string # v v No need to type-cast it to `set`. # v v Python takes care of it >>> ''.join(set(word_1).intersection(word_2)) 'oe'

set 将返回中的唯一字符您的字符串. set.intersection方法将返回两个集合中的共同字符.

set will return the unique characters in your string. set.intersection method will return the characters which are common in both the sets.

如果必须使用for循环,那么您可以使用列表理解:

If for loop is must for you, then you may use a list comprehension as:

>>> unique_1 = [w for w in set(word_1) if w in word_2] # OR # >>> unique_2 = [w for w in set(word_2) if w in word_1] >>> ''.join(unique_1) # Or, ''.join(unique_2) 'oe'

上面的结果也可以通过显式的for循环来实现:

Above result could also be achieved with explicit for loop as:

my_str = '' for w in set(word_1): if w in word_2: my_str += w # where `my_str` will hold `'oe'`

更多推荐

查找两个字符串之间的常见字符

本文发布于:2023-11-02 17:45:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1553014.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字符   常见   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!