python 与GO中操作slice,list的方式实例代码

yipeiwu_com6年前Python基础

python 与GO中操作slice,list的方式实例代码

GO代码中遍历slice,寻找某个slice,统计个数。

type Element interface{}

func main() {
  a := []int{1, 2, 3, 4, 1}

  for _, i := range a {
   fmt.Println(i)
  }
  for i := 0; i < len(a); i++ {
   //fmt.Println(i)
  }
  fmt.Println(index0(a, 3))
  fmt.Println(index0([]string{"a", "b", "c", "d", "e"}, "e"))
  sort.Ints(a) //排序
  fmt.Println(a)

}

//
func index0(a Element, i interface{}) int {

  if b, ok := a.([]int); ok {
   if c, ok1 := i.(int); ok1 {
     for indexC, v := range b {
      if v == c {
        return indexC
      }
     }
   }
  }
  if b, ok := a.([]string); ok {
   if c, ok1 := i.(string); ok1 {
     for indexC, v := range b {
      if v == c {
        return indexC
      }
     }
   }
  }
  return -1
}

可以看到上述的GO语言中slice没有寻找某个元素的方法。我自定义一个方法

下面的python的代码非常简洁了

a=[1,2,3,4,1]
for b in a :
  print(b)
i=0
while i <len(a):
  print(a[i])
  i=i+1
#print( sorted(a)) 方式一排序
a.sort()
print(a)
print( a.index(3))
a.count(1)

感谢阅读,希望能帮助到大家,谢谢大家对本站的 支持!

相关文章

对pandas中两种数据类型Series和DataFrame的区别详解

对pandas中两种数据类型Series和DataFrame的区别详解

1. Series相当于数组numpy.array类似 s1=pd.Series([1,2,4,6,7,2]) s2=pd.Series([4,3,1,57,8],index=['a...

Python中pillow知识点学习

此系列意在记录于一些有趣的程序及对其的总结。 问题来源: https://github.com/Yixiaohan/show-me-the-code https://github.com...

在Python的while循环中使用else以及循环嵌套的用法

循环使用 else 语句 在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 bre...

Python输入二维数组方法

前不久对于Python输入二维数组有些不解,今日成功尝试,记以备忘。这里以输入1-9,3*3矩阵为例 n=int(input()) line=[[0]*n]*n for i in r...

Python实现读取邮箱中的邮件功能示例【含文本及附件】

本文实例讲述了Python实现读取邮箱中的邮件功能。分享给大家供大家参考,具体如下: #-*- encoding: utf-8 -*- import sys import local...