数据容器/数组/集合
Python: 对数据容器的操作
# 对list进行切片,从1开始,4结束,步长1(默认步长为1) my_list = [0, 1, 2, 3, 4, 5, 6] result1 = my_list[1:4] print(f"结果1:{result1}") # 对tuple进行切片,从头开始,到最后结束,步长1 my_tuple = (0, 1, 2, 3, 4, 5, 6) result2 = my_tuple[:] # 其实和结束不写表示从头到尾,步长为1可以省略 print(f"结果2:{result2}") # 对str进行切片,从头开始,到最后结束,步长2 my_str = "01234567" result3 = my_str[::2] print(f"结果3:{result3}") # 对str进行切片,从头开始,到最后结束,步长-1 my_str = "01234567" result4 = my_str[::-1] # 等同于序列反转了 print(f"结果4:{result4}") # 对列表进行切片,从3开始,到1结束,步长-1 my_list = [9, 10, 21, 3, 4, 5, 6] result5 = my_list[3:1:-1] print(f"结果5:{result5}") # 对元组进行切片,从头开始,到尾结束,步长-2 my_tuple = (0, 1, 2, 3, 4, 5, 6) result6 = my_tuple[::-2] print(f"结果6:{result6}")
Java: 对数组的操作
//对list进行切片,从1开始,4结束,补偿1 int[] my_list = {0, 1, 2, 3, 4, 5, 6}; int[] sub_list = Arrays.copyOfRange(my_list, 1, 5); for (int i : sub_list) { System.out.print(i); }
Python: 字典
# 定义字典 my_dict1 = {"王力宏":99, "周杰伦":88, "林俊杰": 77}
score = my_dict1["王力宏"]
print(f"王力宏的考试分数是:{score}")
Java: Map集合
Map<String, Integer> map = new HashMap<>(); map.put("王力宏",99); map.put("周杰伦",88); map.put("林俊杰",77); int score = map.get("王力宏"); System.out.println("王力宏的考试分数是:"+score);
Python: 遍历字典
# 获取全部Key my_dict = {"周杰伦": 99, "林俊杰": 88, "张学友": 77} keys = my_dict.keys() print(f"该字典的全部Keys是:{keys}") # 遍历字典 # 方式1:通过获取全部的Key来完成遍历 for key in keys: print(f"字典的key是:{key}") print(f"字典的value是:{my_dict[key]}") # 方式2:直接对字典进行for循环,每一次循环都是直接得到key for key in my_dict: print(f"2字典的key是:{key}") print(f"2字典的value是:{my_dict[key]}") # 统计字典内的元素数量,len()函数 num = len(my_dict) print(f"字典中的元素数量有:{num}个")
Java: 遍历Map
//遍历Map
Map<String, Integer> map = new HashMap<>();
map.put("王力宏",99);
map.put("周杰伦",88);
map.put("林俊杰",77);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String name = entry.getKey();
int score = entry.getValue();
System.out.println(name + "的考试分数是:" + score);
}
// 统计字典内的元素数量
int size = scores.size();
System.out.println("Map中元素的数量是:" + size);
标签:map,Java,Python,list,语法,key,print,my,字典 From: https://www.cnblogs.com/TylerZhong/p/17728796.html