列表数组操作

Golang

// 切片去重
func listDupRemove(list []int) []int {
	s := make([]int, 0)
	m := make(map[int]bool)
	for _, k := range list {
		if _, ok := m[k]; !ok {
			s = append(s, k)
			m[k] = true
		}
	}
	return s
}
// 切片删除
func listRemove(list []int, e int) []int {
	for i := 0; i < len(list); i++ {
		if list[i] == e {
			list = append(list[:i], list[i+1:]...)
			i--
		}
	}
	return list
}
// 切片合并
s := []int{1, 3, 5}
s2 := []int{3, 4}
list := append(s, s2...)
// 切片排序
s:=[]int{1,4,6,3,2}
sort.Stable(sort.IntSlice(s))
// sort.Reverse(sort.IntSlice(s))降序
// sort.Ints 和 sort.Sort底层用的快速排序(不稳定)
// sort.Stable底层用的插入排序(稳定)
// 切片过滤
func listFilter(list []string, filter func(string) bool) (ls []string) {
	for _, s := range list {
		if filter(s) {
			ls = append(ls, s)
		}
	}

	return
}
filter := func(s string) bool { return !strings.HasPrefix(s, "foo") }
list := listFilter([]string{"abc", "fool", "33"}, filter)

Nodejs

// 数组去重
const s = [1,2,2,5,1]
const ss = [...new Set(s)]
// 数组删除
const s = [3, 4, 5]
const ss = s.filter(e=> e !== 3)
// s.forEach((v,i,arr)=>{
//    if (v===3) {
//        arr.splice(i, 1)
//    }
// })
// 数组合并
const s1 = [1,2]
const s2 = [2,3]
const s = s1.concat(s2)
// s = [...s1, ...s2]
// 数组排序
const s = [3,1,2]
const ss = s.sort((x, y) => x - y)
// 数组过滤
['abc', 'foo', '33'].filter(e => e.indexOf('foo') !== 0) 

Python

# 列表去重
s = [1, 2, 5, 3, 2]
ss = list(set(s))
# 列表删除
s = [3, 5, 6]
s.remove(6)
# del s[1:2]
# 列表合并
s1 = [2, 3]
s2 = [3, 4]
s1.extend(s2)
# s1+s2
# 列表排序
s = [1, 3, 5, 2]
# 升序
s.sort(reverse=False)
# 列表过滤
list = filter(lambda s: not s.startswith(("foo", "33")), ["abc", "foo", "33"])
# startswith 支持元组,也支持start、end坐标,返回bool
# 逻辑非用 not,不能用!

C#

// 列表去重
List<int> s = new List<int>() {{1},{2},{1}};
var ss = s.Distinct().ToList();
// 列表删除
List<string> s = new List<string>() {{1},{3},{1}};
s.Remove(1);
// 列表合并
List<int> s1 = new List<int>() {{1},{3}};
List<int> s2 = new List<int>() {{2}};
var s = s1.Union(s2).ToList();
// 列表排序
List<int> s = new List<int>() {{2},{1},{3}};
s.Sort((x, y) => x - y);
// var ss = s.OrderBy(o => o);
// 数组过滤
string[] list = new string[] {"abc", "foo", "33"};
// 使用.ToArray()转换成数组,否则是个迭代器
string[] ls = list.Where(s => s.IndexOf("foo") != 0).ToArray();

// Select -> map
// Aggregate -> Reduce
posted @ 2022-08-27 09:35  codeIsArt  阅读(21)  评论(0编辑  收藏  举报