【问题标题】:How to print a line if it contains a string from another file?如果一行包含来自另一个文件的字符串,如何打印?
【发布时间】:2017-05-04 18:57:44
【问题描述】:

如果行包含来自另一个文件的字符串,Python如何打印行?

一个文本文件:

test.com
test2.com
test3.com

另一个文本文件:

test.com:user:pass
test3.com:user:pass
test9.com:user:pass

(我从两个文件中得到两个列表)

a = ['test1.com,user,pass','test2.com,user,passw','tes4.com,user,pass']
b = ['test5.com','test1.com','test2.com']

temp = a[:]
for i in range(len(a)):
    temp[i] = temp[i].split(':')[0]
for i in b:
    if i in temp:
        print i

【问题讨论】:

  • 您的问题不清楚。输出应该是什么?
  • 我不是英语,如果包含另一个列表中的字符串,输出应该是列表中的打印项
  • 有什么帮助吗?请
  • 不是英文,但数据是通用的。从给定的输入中显示您期望的确切输出。
  • 我的意思是我的英语不好.....

标签: python list file find


【解决方案1】:
a = ['test1.com,user,pass','test2.com,user,passw','tes4.com,user,pass']
b = ['test5.com','test1.com','test2.com']
temp = a[:]
for i in range(len(a)):
    temp[i] = temp[i].split(',')[0]
for i in range(len(temp)):
    if temp[i] in b:
        print a[i]

这将根据需要打印另一个列表的内容。
test1.com,用户,通过
test2.com,用户,密码

【讨论】:

  • 您是否将 a 和 b 替换为实际的列表名称?如果可以,您能否在问题中添加您的源代码?
  • 并检查倒数第二行是否有这个'if i in temp:',因为我后来更新了
  • 我需要打印 site.com:user:pass 而不是 site.com(所以我需要打印其他列表)很抱歉打扰您
  • 没问题。下次问的时候尽量说清楚。只有在我们能够理解问题的情况下,我们才会在这里提供帮助。
【解决方案2】:

使用列表推导:

a = ['test1.com,user,pass','test2.com,user,passw','tes4.com,user,pass']
b = ['test5.com','test1.com','test2.com']
a =  [i.split(',') for i in a]
final_list = [''.join(i) for i in a if i[0] in b]

print final_list

如果站点存在于列表 b 中,现在会为您提供站点、用户名和密码

【讨论】:

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