字典的运用案列
程序员文章站
2022-05-03 08:06:00
...
字典的运用
1.统计字符串中,各个字符的个数
⽐如:“hello world” 字符串统计的结果为: h:1 e:1 l:3 o:2 d:1 r:1 w:1
1 def count_char(test_str):
2 """统计字符串的个数"""
3 count_dict = {} # 存储统计结果的字典
4 # 用set()函数对集合进行去重
5 for k in set(test_str):
6 count_dict[k] = test_str.count(k)
7 return count_dict
8
9 test_str = input('请输入字符串:')
10 count_dict = count_char(test_str)
11 print(count_dict)
2.给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
#coding=utf-8
class Solution(object):
def twoSum(self,nums,target):
#定义一个空的字典,用来保存数据
dirct_1 = {}
#遍历nums里面的数据
for i in range(0,len(nums)):
num = target - nums[i]
if num not in dirct_1:
dirct_1[nums[i]] = i
else:
return [dirct_1[num],i]
target = 6
nums = [2,3,4]
solution = Solution()
result = solution.twoSum(nums,target)
print(result)