我有一个清单:
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
Run Code Online (Sandbox Code Playgroud)
并希望搜索包含该字符串的项目'abc'.我怎样才能做到这一点?
if 'abc' in my_list:
Run Code Online (Sandbox Code Playgroud)
会检查是否'abc'存在在列表中,但它的一部分'abc-123'和'abc-456','abc'对自己不存在.那么如何获得包含的所有项目'abc'?
在python中,如何检查对象是否是生成器对象?
试试这个 -
>>> type(myobject, generator)
Run Code Online (Sandbox Code Playgroud)
给出错误 -
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'generator' is not defined
Run Code Online (Sandbox Code Playgroud)
(我知道我可以检查对象是否有一个next方法让它成为一个生成器,但我想用一些方法来确定任何对象的类型,而不仅仅是生成器.)
在测试变量有值时,是否有理由决定使用哪一个try或哪些if结构?
例如,有一个函数返回列表或不返回值.我想在处理之前检查结果.以下哪一项更可取,为什么?
result = function();
if (result):
for r in result:
#process items
Run Code Online (Sandbox Code Playgroud)
要么
result = function();
try:
for r in result:
#process items
except TypeError:
pass;
Run Code Online (Sandbox Code Playgroud)
在python中有一个简单的方法来判断某些东西是不是一个序列?我试着这么做:
if x is not sequence但是python并不喜欢这样
可能重复:
在Python中,如何确定对象是否可迭代?
如何检查Python对象是否支持迭代,又称迭代对象(参见定义)
理想情况下,我希望函数类似于isiterable(p_object)返回True或False(建模后isinstance(p_object, type)).
为了更好地解释,请考虑这种简单的类型检查功能:
from collections import Iterable
def typecheck(obj):
return not isinstance(obj, str) and isinstance(obj, Iterable)
Run Code Online (Sandbox Code Playgroud)
如果obj是可迭代类型str,则返回True.但是,如果obj是a str或不可迭代类型,则返回False.
有没有办法更有效地执行类型检查?我的意思是,检查obj一次的类型看是否不是a 似乎有点多余str,然后再次检查它以查看它是否可迭代.
我想除了str像这样列出所有其他可迭代类型:
return isinstance(obj, (list, tuple, dict,...))
Run Code Online (Sandbox Code Playgroud)
但问题是该方法将错过任何未明确列出的其他可迭代类型.
那么......有什么更好的,或者我在函数中给出的方法效率最高?
如何检查对象是否是字符串列表?我只能检查一个对象是否是字符串:
def checktype(obj):
if isinstance(obj,str):
print "It's a string"
obj1 = ['foo','bar','bar','black','sheet']
obj2 = [1,2,3,4,5,'bar']
obj3 = 'bar'
for i in [obj1,obj2,obj3]:
checktype(i)
Run Code Online (Sandbox Code Playgroud)
期望的输出:
It's a list of strings
It's not a list of strings or a single string
It's a single string
Run Code Online (Sandbox Code Playgroud) 我已经看到一些帖子推荐isinstance(obj, collections.Sequence)而不是hasattr(obj, '__iter__')确定某些内容是否是列表.
len(object)或hasattr(object,__iter__)?
起初我很兴奋,因为测试一个物体__iter__对我来说总是很脏.但经过进一步审查后,这似乎仍然是最好的解决方案,因为没有一个isinstance测试collection产生相同的结果.collections.Sequence是接近但它返回True字符串.
hasattr(obj, '__iter__')
set([]): True
{}: True
[]: True
'str': False
1: False
isinstance(obj, collections.Iterable)
set([]): True
{}: True
[]: True
'str': True
1: False
isinstance(obj, collections.Iterator)
set([]): False
{}: False
[]: False
'str': False
1: False
isinstance(obj, collections.Sequence)
set([]): False
{}: False
[]: True
'str': True
1: False
Run Code Online (Sandbox Code Playgroud)
这是我用来生成这个的代码:
import collections
testObjs = [
set(),
dict(),
list(),
'str',
1
] …Run Code Online (Sandbox Code Playgroud) 是否有更好的方法来编写以下内容:
row_counter = 0
for item in iterable_sequence:
# do stuff with the item
counter += 1
if not row_counter:
# handle the empty-sequence-case
Run Code Online (Sandbox Code Playgroud)
请记住,我不能使用len(iterable_sequence),因为1)并非所有序列都具有已知长度; 2)在某些情况下,调用len()可能会触发将序列的项加载到内存中(与sql查询结果一样).
我问的原因是,我只是好奇是否有办法让上面更简洁和惯用.我正在寻找的是:
for item in sequence:
#process item
*else*:
#handle the empty sequence case
Run Code Online (Sandbox Code Playgroud)
(假设"else"在这里仅适用于空序列,我知道它没有)
我经常从我的 Python 代码中得到未捕获的异常(错误),这些异常被描述为TypeErrors. 经过大量的实验和研究,我收集了以下示例(以及细微的变化):
TypeError: func() takes 0 positional arguments but 1 was given
TypeError: func() takes from 1 to 2 positional arguments but 3 were given
TypeError: func() got an unexpected keyword argument 'arg'
TypeError: func() missing 1 required positional argument: 'arg'
TypeError: func() missing 1 required keyword-only argument: 'arg'
TypeError: func() got multiple values for argument 'arg'
TypeError: MyClass() takes no arguments
TypeError: unsupported operand type(s) for +: 'int' and 'str'
TypeError: can only concatenate str …Run Code Online (Sandbox Code Playgroud) python ×10
collections ×1
debugging ×1
for-loop ×1
generator ×1
if-statement ×1
isinstance ×1
iterable ×1
iterator ×1
python-3.x ×1
sequence ×1
sequences ×1
syntax ×1
typechecking ×1
typeerror ×1
types ×1