zoukankan      html  css  js  c++  java
  • Python:fromkeys()方法

    简介

    Python 字典(Dictionary) fromkeys() 函数用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值。

    语法

    fromkeys()方法语法:

    dict.fromkeys(seq[, value])

    参数

    • seq -- 字典键值列表
    • value -- 可选参数, 设置键序列(seq)的值

    返回值

    该方法返回列表。

    实例一:展示了 fromkeys()函数的使用方法:

    #!/usr/bin/python 
    seq = ('name', 'age', 'sex') 
    dict = dict.fromkeys(seq)
    #不赋值 
    print "New Dictionary : %s" % str(dict) 
    #赋值10
    dict = dict.fromkeys(seq, 10) 
    print "New Dictionary : %s" % str(dict)
    
    #输出结果:
    New Dictionary : {'age': None, 'name': None, 'sex': None} 
    New Dictionary : {'age': 10, 'name': 10, 'sex': 10}

    实例二:请统计字符串in_str里面每个元音字母各出现了多少次

    # string of vowels
    vowels = 'aeiou'
    counter = {}.fromkeys(vowels,0)
    
    # change this value for a different result
    in_str = 'Hello, have you tried our turorial section yet?'
    
    # make it suitable for caseless comparisions
    in_str = in_str.casefold()
    
    # make a dictionary with each vowel a key and value 0
    # count the vowels
    for char in in_str:
      if char in counter:
        counter[char] += 1
    
    print(counter)

    #输出结果
    {'a': 2, 'e': 5, 'i': 3, 'o': 5, 'u': 3}
     
  • 相关阅读:
    2021广东省强网杯WriteUp
    2021 数字四川创新大赛WriteUp
    2021 陇剑杯wp
    2021 羊城杯WriteUP
    如何翻安全四大顶会的文章
    2021 祥云杯 wp
    codeql初探
    sqlmap应用
    sql注入2
    sql注入
  • 原文地址:https://www.cnblogs.com/kumata/p/9094671.html
Copyright © 2011-2022 走看看