首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python中的For循环没有正确地将列表划分为子集

Python中的For循环没有正确地将列表划分为子集
EN

Stack Overflow用户
提问于 2019-06-27 01:37:28
回答 4查看 64关注 0票数 1

Python新手如此赤裸裸。

我正在尝试找到一种方法来确定一个包含字符串和变量的列表是否是另一个列表的子集。到目前为止,请查看下面的代码和结果

代码语言:javascript
复制
y = ['test_sam_20190624.csv', 'test_phil_20190624.csv', 'test_bill_20190624.csv', 'test_jess_20190624.csv', 'test_issy_20190624.csv', 'test_clinton_20190624.csv']
x = ['sam', 'jack', 'bill', 'rodry', 'clinton']
print('\nFile list is ')
print(*y, sep="\n")
print('\nNeeded names are ')
print(*x, sep="\n")

datetoday = '20190624'

incl = [p for p in x if 'test'+p+datetoday+'.csv' in y]
not_incl = [p for p in x if 'test'+p+datetoday+'.csv' not in y]

print("\n Included")
print(*incl, sep="\m")
print("\n Not included")
print(*not_incl, sep="\n")

和下面给出的输出:

代码语言:javascript
复制
File list is 
test_sam_20190624.csv
test_phil_20190624.csv
test_bill_20190624.csv
test_jess_20190624.csv
test_issy_20190624.csv
test_clinton__20190624.csv

Needed names are 
sam
jack
bill
rodry
clinton

 Included


 Not included
sam
jack
bill
rodry
clinton

Process finished with exit code 0

但我肯定会期望incl = ['sam' 'bill 'clinton']作为输出?输出为:

代码语言:javascript
复制
 Included
sam
bill
clinton


 Not included
jack
rodry

我哪里错了?也许在字符串的连接中?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2019-06-27 01:45:17

您没有在搜索中包含完整的字符串:

代码语言:javascript
复制
incl = [p for p in x if 'test'+'_'+p+'_'+datetoday+'.csv' in y]
not_incl = [p for p in x if 'test'+'_'+p+'_'+datetoday+'.csv' not in y]

您在查找中忘记了下划线。

代码语言:javascript
复制
[dkennetz@nodecn203  fun]$ python3.5 fun.py

File list is
test_sam_20190624.csv
test_phil_20190624.csv
test_bill_20190624.csv
test_jess_20190624.csv
test_issy_20190624.csv
test_clinton_20190624.csv

Needed names are
sam
jack
bill
rodry
clinton

 Included
sam\mbill\mclinton

 Not included
jack
rodry
票数 2
EN

Stack Overflow用户

发布于 2019-06-27 01:47:29

您似乎忘记了串联中的_%s。

试着改变:

代码语言:javascript
复制
incl = [p for p in x if 'test'+p+datetoday+'.csv' in y]

代码语言:javascript
复制
incl = [p for p in x if 'test_'+p+'_'+datetoday+'.csv']

Not_incl也是如此:

代码语言:javascript
复制
not_incl = [p for p in x if 'test'+p+datetoday+'.csv' not in y]

应该是

代码语言:javascript
复制
not_incl = [p for p in x if 'test_'+p+'_'+datetoday+'.csv' not in y]

现在你应该得到想要的输出了。

票数 2
EN

Stack Overflow用户

发布于 2019-06-27 01:56:01

if语句中缺少下划线(_)。它应该如下所示。

代码语言:javascript
复制
incl = [p for p in x if 'test_'+p+'_'+datetoday+'.csv' in y]
not_incl = [p for p in x if 'test_'+p+'_'+datetoday+'.csv' not in y]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56778342

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档