'if'语句中的多个条件('和'&'或'?)

Mar*_*k K -1 python if-statement

我想过滤符合以下条件的行:

  1. 字符'/'在行中
  2. 人物';' 在线
  3. 字符'e'在行中
  4. 字符'k'不在行中
  5. 字符'@'不在行中
  6. 线的长度不超过80

我有的是:

the_list = ['C  TEE edBore 1 1/4200;',
'Cylinder SingleVerticalB HHJ e 1 1/8Cooling 1',
'EngineBore 11/1; TDT 8Length 3Width 3',
'EngineCy HEE Inline2008Bore 1',
'Height 4TheChallen TET e 1Stroke 1P 305',
'Height 8C ;0;Wall15ccG QBG ccGasEngineJ 142',
'Height EQE C ;0150ccGas2007',
'Length 10Wid ETQ Length 10Width ',
'Stro EHT oke 1 1/8Length ',
'Stroke 1 1/4HP   JII Stroke 1 1/4HP  ',
'Stroke 1Cy QTH 7Weight ; 1/2LBS',
'Weight 18LBSLength 1 DQT Length 12Width 7',
'Width 4L 233He TTE 3Height ;Weight ',
'Width ;Height 9200;Weight 4L APO .75H.P.@;5200RPM']


for a in the_list:
    if '/' in a and ';' in a and 'e' in a and '@' not in a and 'k' not in a and len(a)<80:
        print a
Run Code Online (Sandbox Code Playgroud)

'if'语句看起来并不聪明.有什么好办法呢?

mu *_*u 無 5

您可以使用anyall关键字:

for line in the_list:
    if all(ch in line for ch in '/;e') and \
            not any(ch in line for ch in 'k@') and \
            len(line) <= 80:
        print line
Run Code Online (Sandbox Code Playgroud)

结果输出:

C  TEE edBore 1 1/4200;
EngineBore 11/1; TDT 8Length 3Width 3
Run Code Online (Sandbox Code Playgroud)