【问题标题】:Comparing two strings created from lists比较从列表创建的两个字符串
【发布时间】:2017-07-22 13:22:04
【问题描述】:

我想比较来自两个不同列表 d1 和 d2 的两个字符串。 如果来自 d1 的字符串与 d2 相似,则返回相似的字符串。

这是我的代码:

d1 = [['learn'],['car']]
d2 = [['learn'],['motor']]

str1 = ', '.join(str(i) for i in d1)
str2 = ', '.join(str(j) for j in d2)

for i in str1:
    for j in str2:
        if i == j:
            print str1, str2

但输出是:

['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']
['learn'], ['car'] ['learn'], ['motor']

我希望输出是:

['learn','learn']

^ 它来自 str1 和 str2 中的相似字符串。

谁能帮忙?

【问题讨论】:

  • 试试:print i, j
  • 我不明白你在追求什么。您是否正在寻找两个列表的交集?即出现在两个列表中的元素。
  • 它认为他是。

标签: python string list for-loop if-statement


【解决方案1】:

这样的事情怎么样:

d1 = [['learn'],['car']]
d2 = [['learn'],['motor']]
for elem in d1:
  if elem in d2:
    print([elem[0],elem[0]])

【讨论】:

    【解决方案2】:

    使用zip的简单解决方法。关于zip

    for i,j in zip(d1,d2):
    if i==j:
        print i,j
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多