我一直在用Python进行字典练习,而且我对语言和编程本身也很陌生.我一直在尝试取一个字符串或字符串列表,并让我的代码比较字符串的第一个字母,并用字母表中的某个字母开出多少个字符串.这是我到目前为止:
d = {}
text=["time","after","time"]
# count occurances of character
for w in text:
d[w] = text.count(w)
# print the result
for k in sorted(d):
print (k + ': ' + str(d[k]))
Run Code Online (Sandbox Code Playgroud)
我的目标是,例如得到以下结果:
count_starts(["time","after","time"]) -->{'t': 2, 'a': 1}
Run Code Online (Sandbox Code Playgroud)
但是,我得到的更像是以下内容:
count_starts(["time","after","time"]) --> {time:2, after:1}
Run Code Online (Sandbox Code Playgroud)
凭借我所拥有的,我已经能够计算出一个完整的唯一字符串出现的次数,而不是计算字符串中的第一个字母.
我也尝试过以下方法:
d = {}
text=["time","after","time"]
# count occurances of character
for w in text:
for l in w[:1]:
d[l] = text.count(l)
# print the result
for k in sorted(d):
print (k + ': ' + str(d[k])) …Run Code Online (Sandbox Code Playgroud) 我正在翻阅字典并试图通过它并确定"food_type"中的哪些字典键具有相应的"fruit"值.到目前为止,我的下面最远的代码是:
def fruit (food_type):
for f in food_type.values():
if f=="fruit" :
return(f)
fruit ({'apple': 'fruit', 'lettuce': 'veggie', 'banana':'fruit'})
Run Code Online (Sandbox Code Playgroud)
这只会返回"水果"一次,所以我不是100%,如果这就是我想要的,因为我的最终目标是将值反映回字典并返回具有"水果"作为其值的键.我知道为了得到一个你可以做的值:d [k]或d.get(k)等.
我正在寻找以下输出:
["apple","banana"]
Run Code Online (Sandbox Code Playgroud) 我正在翻阅一本字典,其中以总统的名字作为我字典的关键字,以及一个元组,其中包含年份开始,服务年限,学期开始时的年龄以及他们来自哪个州.在这种情况下,我只是看看他们为此开始任期的年龄.dictonary的样本:
pres_data={"Reagan": (1981, 8, 69,"California"), "Bush":(1989, 4,64,"Texas")}
Run Code Online (Sandbox Code Playgroud)
字典经历了更多的总统和数据,如上所述,但我不包括它,因为它在这里太多了.
我正在寻找的输出是:
(64,["George Bush"])
Run Code Online (Sandbox Code Playgroud)
所以它将首先显示最小年龄(我假设将使用min()函数来获取它,但它尚未在我的设置中工作)然后是一个共享的总统名称列表那个词典中最年轻的.
我的代码到目前为止:
pres_data={"Reagan": (1981, 8, 69,"California"), "Bush":(1989,4,64,"Texas")}
for key, value in pres_data.items():
age_start_term=value[2]
print(age_start_term,key)
Run Code Online (Sandbox Code Playgroud)
我想在我的age_start_term变量之后放置像youngest = min(age_start_term)这样的东西,但这只会检查那一次迭代.所以我想我都希望得到最小的比较,然后打印一个列表,其中包含与词典中表示的最年轻年龄一致的键.为什么我可以添加到我所拥有的内容中,以便在迭代后将其与所有年龄段进行比较?为了获得与字典中最年轻的年龄相对应的键,我可以沿着这些方向做点什么吗?
allyoungest= [k for k in pres_data if pres_data[k] == #variable representing youngest]
Run Code Online (Sandbox Code Playgroud)