本文介绍了检查列表是否包含 int、str、tuple 和 sub-list 的优雅方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些脚本,但我必须添加一些条件;用户放置一个列表,它必须至少包含这些类型中的一种(元组、整数、s tr 和子列表).

没有 4 if 有没有一种优雅的方法来做到这一点?

我考虑过 for 循环并使用 isinstance(i, type) 但它很棘手,因为它一遍又一遍地运行并询问有关一种类型的不同问题"

for i in List:如果 isinstance(i,int):如果 isinstance(i,str)

如您所见,这不是很优雅.我想过为每种类型添加新变量 i,j,k 并且可能做 4 个 for 循环:

for为了为了为了

欢迎提供任何想法和线索.谢谢!

解决方案

isinstance 可以使用不同类型的元组:

>>>isinstance('a', (str, list, tuple, int))真的

结合any

>>>数据 = [1, 'a', (2, 4, 6)]>>>any(isinstance(x, (str, list, tuple, int)) for x in data)真的

或者,如果你想对这些类型的对象做一些事情:

 for x in data:如果 isinstance(x, (str, list, tuple, int)):打印('找到')

I wrote some script, but I have to add some condition; the user puts a list and it must contain at least one of these types (tuple, int,s tr and sub-list).

Is there an elegant way to do that without 4 if?

I thought about for loop and using isinstance(i, type) but its tricky, because it runs over and over and ask the different 'questions' about one kind of type

for i in List:
  if isinstance(i,int):
    if isinstance(i,str)

As you see this is not very elegant. I thought about putting new variable i,j,k for each kind of type and maybe do 4 for loops:

for
  for
   for
    for

Any ideas and clues are welcomed. Thanks!

解决方案

You can use a tuple of different types with isinstance:

>>> isinstance('a', (str, list, tuple, int))
True

Combine with any

>>> data = [1, 'a', (2, 4, 6)]
>>> any(isinstance(x, (str, list, tuple, int)) for x in data)
True

or, if you want to do something with the objects of one these types:

for x in data:
    if isinstance(x, (str, list, tuple, int)):
        print('found')

这篇关于检查列表是否包含 int、str、tuple 和 sub-list 的优雅方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 12:56