gpt4 book ai didi

python - 查找列表中包含字符串的元素的索引

转载 作者:行者123 更新时间:2023-12-01 04:22:23 27 4
gpt4 key购买 nike

例如,该列表包含:

  • 2 个字符串
  • 1 个整数
  • 1 bool
  • 1 个嵌套列表

示例:

["string1", 34, True, "string2", [2,4,6]]

问题:如何找到这两个字符串在列表中的索引? (列表中的对象类型必须被视为未知)

最佳答案

使用isinstance():

my_list = [True, 10.8, [1,2,3], False, True, "Hello", 12, "Sbioer", 2.5]

for i, item in enumerate(my_list):
if isinstance(item, basestring):
print i

输出:

5
7

但是,如果您想检查 int 值,您也会获得 bool 类型项目的索引,因为(引用其他来源的文本):

It is perfectly logical, if you were around when the bool type was added to python (sometime around 2.2 or 2.3).

Prior to introduction of an actual bool type, 0 and 1 were the official representation for truth value, similar to C89. To avoid unnecessarily breaking non-ideal but working code, the new bool type needed to work just like 0 and 1. This goes beyond merely truth value, but all integral operations. No one would recommend using a boolean result in a numeric context, nor would most people recommend testing equality to determine truth value, no one wanted to find out the hard way just how much existing code is that way. Thus the decision to make True and False masquerade as 1 and 0, respectively. This is merely a historical artifact of the linguistic evolution.

因此,如果您只想检查 int 值:

my_list = [True, 10.8, [1,2,3], False, True, "Hello", 12, "Sbioer", 2.5]

for i, item in enumerate(my_list):
if isinstance(item, int) and not isinstance(item, bool):
print i

关于python - 查找列表中包含字符串的元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33558129/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com