【问题标题】:I am New to Python so I don't know how to do this我是 Python 新手,所以我不知道该怎么做
【发布时间】:2022-11-17 18:21:42
【问题描述】:

a=[1,3,4,5,6,7,8,9,2,"里克",56,"打开"]

我想创建一个程序,为您提供字符串在列表中的位置。

【问题讨论】:

标签: python


【解决方案1】:

您应该在这里阅读更多关于您可以在列表上执行的操作:https://docs.python.org/3/tutorial/datastructures.html#more-on-lists

在这种情况下,您可以使用 index() 函数来获取列表中特定项目的索引:

a=[1,3,4,5,6,7,8,9,2,"rick",56,"open"]
print(a.index(7))
print(a.index("rick"))

输出:

5
9

请记住,这些索引是从 0 开始的,因此索引 5 实际上是列表的第 6 个元素,而索引 9 是第 10 个元素。

【讨论】:

    【解决方案2】:
    a=[1,3,4,5,6,7,8,9,2,"rick",56,"open"]
    def find_str(arr):
        res = {}
        for index, value in enumerate(arr):
            if isinstance(value, str):
                res[value] = index
        return res
    

    或者只是作为一个快捷方式:

     def find_str(arr):
        return {value:index for index, value in enumerate(arr) if isinstance(value, str)}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 1970-01-01
      • 2021-03-15
      • 2022-01-08
      • 2014-02-28
      • 2020-02-19
      • 1970-01-01
      相关资源
      最近更新 更多