我有一个从数据库中的两个字段读取的值字典:字符串字段和数字字段.字符串字段是唯一的,因此这是字典的键.
我可以对键进行排序,但是如何根据值进行排序?
注意:我已阅读Stack Overflow问题如何按Python中字典的值对字典列表进行排序?并且可能可以更改我的代码以获得字典列表,但由于我不需要字典列表,我想知道是否有更简单的解决方案.
我们假设有一个列表a = [1, 3, 5, 6, 8].
我想在该列表上应用一些转换,我想避免按顺序执行它,所以map(someTransformationFunction, a)通常可以做到这一点,但是如果转换需要了解每个对象的索引呢?
例如,假设每个元素必须乘以其位置.所以列表应该转换为a = [0, 3, 10, 18, 32].
有没有办法做到这一点?
我正在尝试将我的代码编译成Python 3模块.我在IDLE中选择"运行模块"时运行正常,但在尝试创建分发时收到以下语法错误:
File "/usr/local/lib/python3.2/dist-packages/simpletriple.py", line 9
def add(self, (sub, pred, obj)):
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助指出语法有什么问题吗?这是完整的代码:
import csv
class SimpleGraph:
def __init__(self):
self._spo = {}
self._pos = {}
self._osp = {}
def add(self, (sub, pred, obj)):
"""
Adds a triple to the graph.
"""
self._addToIndex(self._spo, sub, pred, obj)
self._addToIndex(self._pos, pred, obj, sub)
self._addToIndex(self._osp, obj, sub, pred)
def _addToIndex(self, index, a, b, c):
"""
Adds a triple to a specified index.
"""
if a not in index: index[a] = {b:set([c])}
else: …Run Code Online (Sandbox Code Playgroud) 我有两个单词,一个是用户输入字符串,另一个是从文本文件中随机选择的单词.我想返回两个stings中相等的计数值并共享相同的字符串索引.例如,word1 ='bleed',word2 = slice:similar = 1.
word1 = 'frog'
word2 = 'friend'
correct = 0
if len(word1) > len(word2):
for i in range(len(word2)):
if word1[i] == word2[i]:
correct =+ 1
else:
correct == 0
else:
for i in range(len(word1)):
if word1[i] == word2[i]:
correct =+ 1
else:
correct == 0
Run Code Online (Sandbox Code Playgroud)
我是编程的新手,不幸的是我的尝试最大限度地输出了正确= 1.对于我在示例青蛙和朋友中使用的单词我希望看到正确= 2,我的代码产生正确= 1.我如何添加到正确,超过1?谢谢