简体   繁体   English

检查列表是否包含给定元素

[英]Check a list contains given elements

I want to check if my list's first four elements are digits.我想检查我的列表的前四个元素是否是数字。 what i did is as follows:我所做的如下:

myList = ['0', '3', '2', '7', 'O', 'K', 'P']
if myList[0:4] in string.digits:
  print('okay')
else:
  print('wrng')

But this gives the following error.但这会产生以下错误。

TypeError: 'in <string>' requires string as left operand, not list

How can I achieve this?我怎样才能做到这一点?

The error is telling you that you can't do some_list in some_string - after all, a list consists of characters, not lists, so it's pointless.该错误告诉您不能在some_list in some_string - 毕竟,列表由字符组成,而不是列表,因此毫无意义。 You want to check if all the characters in your list are in the string, so:您想检查列表中的所有字符是否都在字符串中,因此:

if all(ch in string.digits for ch in myList[:4]):

The 0 in 0:4 is not needed, it's the default. 0 0:4中的 0 不需要,它是默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM