小编use*_*865的帖子

查找内置Python函数的源代码?

有没有办法看到内置函数如何在python中工作?我不是指如何使用它们,而是它们是如何构建的,排序枚举背后的代码是什么......?

python python-internals

114
推荐指数
8
解决办法
9万
查看次数

在python中使用文本文件

我试图采取一个文本文件,并在python中只使用它的前30行.这就是我写的:

text = open("myText.txt")
lines = myText.readlines(30)
print lines
Run Code Online (Sandbox Code Playgroud)

出于某种原因,当我打印时,我得到超过150行?我究竟做错了什么?

python

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

列表中的位置.蟒蛇

可以说我有这个清单:

   lst =  [[0], [0, 0], [0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0]...]
Run Code Online (Sandbox Code Playgroud)

我如何根据它在列表中的位置为每个单元格添加一定数量的exapmle:我想通过将3与列表中的位置*嵌套列表中的位置相加来为每个单元格添加公式,所以让我们说第二个单元格在第三个名单上将是

                            3*3*2
(random number)*(the third nested list)*(second spot on that list)
Run Code Online (Sandbox Code Playgroud)

所以最终列表看起来像那样(仅限3号)

   lst =  [[3], [6, 12], [9, 18, 27], [12, 24, 36, 48], [15, 30, 45, 60, 75]...]
Run Code Online (Sandbox Code Playgroud)

无论如何,这只是一个例子,我一般都在询问如何应用某个公式来考虑列表中嵌套列表和内部单元格的位置.它有点难以解释所以我希望它足够清楚.谢谢.

python

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

python:创建一个字典

假设我有一个字符串列表:

["dog", "cat" ,"boy", "cat", "car", "bus",....]
Run Code Online (Sandbox Code Playgroud)

我想把它转换成这样的字典:

{"dog": ["cat"], "cat":["boy","car"], "boy": ["cat"], "car":["bus"]....}
Run Code Online (Sandbox Code Playgroud)

将列表中的每个字符串转换为键并将以下字符串作为列表转换为值的最佳方法是什么?有时候我用相同的键得到的值很少,所以我想把它们放在一起(比如上面字典的第二个索引).

python dictionary

0
推荐指数
1
解决办法
224
查看次数

结合字符串

假设我有两个字符串列表,我想通过组合两个列表来创建一个新列表,这样第一个列表中的第一个字符串将位于第二个列表中第一个字的元组中,第二个列表中的第二个字符串等......

仅举例如:

input: lst1 = ["hello", "first", "is"]
input: lst2 = ["my", "name", "tom"]
output: [("hello","my"), ("first", "name"), ("is", "tom")]
Run Code Online (Sandbox Code Playgroud)

我写了类似的东西:

lst1 = ["hello", "first", "is"]
lst2 = ["my", "name", "tom"]
new_list = []
    for i in lst1 :
            for j in lst2 :
                    two_words = (i, j)
                    new_list.append(two_words)
    return new_list
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

python

0
推荐指数
1
解决办法
686
查看次数

比较Python中的类实例

我在python中建立了一个新类,它用6位数字定义时间(例如18:45:00)

class Time(object):

    def __init__(self, hour, minute, second):
        minute = minute + second / 60
        hour = hour + minute / 60        
        self.hour = hour % 24
        self.minute = minute % 60
        self.second = second  % 60
Run Code Online (Sandbox Code Playgroud)

我还定义了许多方法来使其正常工作。我遇到的问题是 cmp 方法:

def __cmp__(self,other):
    return cmp(self.to_seconds(),other.to_seconds())
Run Code Online (Sandbox Code Playgroud)

当我尝试比较时间时它工作得很好,如果我对时间列表进行排序它也工作得很好。但是,如果我尝试对时间和整数或字符串列表进行排序,它也可以工作。我如何将其定义为仅比较时间,并在尝试将时间与其他时间进行比较时引发错误。

python

0
推荐指数
1
解决办法
4344
查看次数

标签 统计

python ×6

dictionary ×1

python-internals ×1