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

标签 python

例如,该列表包含:

  • 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/

相关文章:

python - 如何像 Python 中的原始字符串一样处理返回/存储的字符串?

python - 从 pd.series 格式的列中分割字符串 python

python Pandas : how to find rows in one dataframe but not in another?

python - Matplotlib 保存文件稍后在 ipython 中重新编辑

python - 为一组组合建立最高分

python - 将 sigmoid 结果解释为神经网络中的概率

python - Pandas 数据帧 : loop and calculate mean and std over increasing number of columns

python - 在 python 脚本中使用 youtube-dl 仅从 youtube 视频下载音频

python sklearn pipiline 适合 : "AttributeError: lower not found"

Python 词典列表 [int : tuple] Sum