相关疑难解决方法(0)

如何按值对字典进行排序?

我有一个从数据库中的两个字段读取的值字典:字符串字段和数字字段.字符串字段是唯一的,因此这是字典的键.

我可以对键进行排序,但是如何根据值进行排序?

注意:我已阅读Stack Overflow问题如何按Python中字典的值对字典列表进行排序?并且可能可以更改我的代码以获得字典列表,但由于我不需要字典列表,我想知道是否有更简单的解决方案.

python sorting dictionary

3424
推荐指数
31
解决办法
249万
查看次数

我可以在map函数中使用索引信息吗?

我们假设有一个列表a = [1, 3, 5, 6, 8].

我想在该列表上应用一些转换,我想避免按顺序执行它,所以map(someTransformationFunction, a)通常可以做到这一点,但是如果转换需要了解每个对象的索引呢?

例如,假设每个元素必须乘以其位置.所以列表应该转换为a = [0, 3, 10, 18, 32].

有没有办法做到这一点?

python python-2.7 map-function

30
推荐指数
3
解决办法
1万
查看次数

嵌套参数不编译

我正在尝试将我的代码编译成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)

python compatibility python-2.x python-3.x

23
推荐指数
1
解决办法
3554
查看次数

迭代两个字符串,当相同索引处的字符匹配时返回计数

我有两个单词,一个是用户输入字符串,另一个是从文本文件中随机选择的单词.我想返回两个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?谢谢

python

3
推荐指数
1
解决办法
1639
查看次数