小编Inb*_*ose的帖子

为什么"打印"运行命令两次?

所以我有这个代码,它返回有关该文件的一系列信息.它返回两次输出,如第二个片段所示.

list = os.listdir(".")
print Style.BRIGHT + "size        info        last-accessed    last-changed     filename" + Style.RESET_ALL
for f in list:
    info = os.stat(f)
    # "  size          info        last-accessed    last-changed     filename
    print " ", info[ST_SIZE], "                                                  " + f
Run Code Online (Sandbox Code Playgroud)

并输出:

  size        info        last-accessed    last-changed     filename
  6243                                                   .bash_history
  55                                                   .bash_profile
  3                                                   .CFUserTextEncoding
  15364                                                   .DS_Store
  102                                                   .fontconfig
  105                                                   .sh_history
  102                                                   .ssh
  442                                                   .Trash
  0                                                   .Xauthority
  105                                                   console
  6688                                                   console.py
  272                                                   Desktop
  238                                                   Documents
  442                                                   Downloads
  2924                                                   Folder
  1156                                                   Library
  204                                                   Movies
  102                                                   Music
  136                                                   Pictures …
Run Code Online (Sandbox Code Playgroud)

python

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

试图从文件中创建一个python字典,但我不断收到"太多的值来解压"这样的错误

我有一个文本文件保存在记事本中,但移动到我的python文件夹,左边有一个国家的三个字母的缩写词,然后右边有四到五个空格,它有一个与之对应的国家:

AFG阿富汗
ARM亚美尼亚

我需要字典使用三个字母作为关键,而国家是价值.它有每个参加奥运会的国家.这是我的代码到目前为止的样子:

def country(fileName):
    infile = open(fileName,'r')
    countryDict = {}
    for line in infile:
        key,value = line.split()
        countryDict[key] = value
    print(countryDict)
    return countryDict
country('CountryCodes.txt')
Run Code Online (Sandbox Code Playgroud)

python dictionary file function

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

dict.keys()返回dict_keys类 - 期望的视图对象

我在Python 2.7.3和Python 3.2.3中运行以下代码:

test_dict = {'foo':'bar'}
type(test_dict.keys())
Run Code Online (Sandbox Code Playgroud)

在Python 2中,输出是:

<type 'list'>
Run Code Online (Sandbox Code Playgroud)

在Python 3中:

<class 'dict_keys'>
Run Code Online (Sandbox Code Playgroud)

但是,Python 3文档声明该keys方法应该返回一个视图对象,那么为什么要返回一个类呢?

dictionary python-3.x

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

正则表达式可调用迭代器获取长度

假设我有以下代码:

>>> a = re.finditer("(?P<char>\w)","hello world")
>>> for i in a:
    print i.groupdict()


{'char': 'h'}
{'char': 'e'}
{'char': 'l'}
{'char': 'l'}
{'char': 'o'}
{'char': 'w'}
{'char': 'o'}
{'char': 'r'}
{'char': 'l'}
{'char': 'd'}
Run Code Online (Sandbox Code Playgroud)

如您所见,有结果,一切都很棒!但是,我希望能够知道,len(a)所以我会这样做:

>>> len(a)
Traceback (most recent call last):
  File "<pyshell#79>", line 1, in <module>
    len(a)
TypeError: object of type 'callable-iterator' has no len()
Run Code Online (Sandbox Code Playgroud)

我的问题是,我如何获得 的长度a,或者更一般地说,我如何获得可调用迭代器的长度,以便我可以在解析它们之前知道是否有任何结果。

python regex iterator

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

如何从另一个类中的一个类调用方法

我在一个文件中有两个类.

主类将具有更新该类中的UI元素的方法.它创建另一个类的实例.

我想在另一个被实例化的类中更新主类中的UI.

class Add(QtGui.QMainWindow,Ui_AddShotDetails):

    def __init__(self):

        super(Add,self).__init__()
        self.setupUi(self)

    def addDetails(self):

        #Do some stuff and call method in Manager class
        Manager.EpiChange() # I get the error at this line

class Manager(QtGui.QMainWindow,Ui_ShotManager):

    def __init__(self):

        super(Manager,self).__init__()
        self.setupUi(self)
        self.AddWindow = Add()

    def EpiChange(self):

        Manager.EpiCode = str(self.cmb_Epi.currentText())
        # Update ui elements

    def addShot(self):

        self.AddWindow.show()

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    win = Manager()
    win.show()
    sys.exit(app.exec_())        
Run Code Online (Sandbox Code Playgroud)

我得到以下Traceback

Traceback (most recent call last):
  File "D:\Manager.py", line 18, in addDetails
    Manager.EpiChange()
TypeError: unbound method EpiChange() must …
Run Code Online (Sandbox Code Playgroud)

python oop class pyqt4

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

为什么我的python函数不会返回任何条件,除了None之外?

我正在制作一个简单的RPG战斗系统,用这个功能来决定玩家将使用哪种类型的攻击.但我没有运气让我的条件返回他们指定的字符串.所有它返回的都是"无"字样.

顺便说一下,我刚开始学习一个月前的编程,所以我不太了解Python.

def attack_or_critical_attack_or_missed():
    #Random number generated from a range and then placed into a list.
    import random
    number_list = [random.randrange(1, 105)]
    print(number_list)
    print("")
    #Check list to see where my generated number gets put. 
    #Big Chance For Regular Attack
    range1 = []
    n = range(1, 76)
    for n in n:
        range1.append(n)
    if range1 in number_list:
        return "normal_attack"
    #Small Chance For A Critical Attack
    range2 = []
    j = range(76, 101)
    for j in j:
        range2.append(j)
    if range2 in number_list:
        return …
Run Code Online (Sandbox Code Playgroud)

python list range python-3.x

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

为什么Vector不会排序?

我在oj上解决了一个问题.但突然间我发现这vector<char*>不符合我的目的.我究竟做错了什么?如果有人能让我明白这个问题......问题描述很简单,你只需要从输入文件中取出并对其进行排序.这是我所做的,但它不会排序:

vector<char*>V;
char str[501][201];
int l=0;
char str1[]= {'~','.','\n','\r',' ','!','@','#','$','%','^','&','*','(',')','+','-','_','=','{','}','[',']',':',';','"','<','>','?','/','|'};
while(gets(str[l++]))
{

    for(int i=0; str[l-1][i]; i++)
    {
        if(str[l-1][i]>='A' && str[l-1][i]<='Z')str[l-1][i]=str[l-1][i]-'A'+'a';
    }
    char *pch;
    pch=strtok(str[l-1],str1);
    while(pch!=NULL)
    {
        // printf("%s\n",pch);
        V.push_back(pch);
        pch=strtok(NULL,str1);
    }
}

sort(V.begin(),V.end());

for(vector<char*>::iterator it=V.begin(); it!=V.end(); it++)
    cout<<*it<<endl;
Run Code Online (Sandbox Code Playgroud)

c++ sorting vector

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

将行拆分为类别和文本

我的列表看起来像这样:

foo = ["neg * , This is a sentence","pos * , This is another sentence"]
Run Code Online (Sandbox Code Playgroud)

我需要将句子分成一个值,即一个值将成为类别,neg或者pos一个句子.我试过了:

for text in foo:
    text = text.split("*")
    for a,b in text:
        cat=a
        text=b
Run Code Online (Sandbox Code Playgroud)

但是我得到了"太多的价值来打开包装",任何人都有一个想法?

python split

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

Python - 所有彩票组合 - 按顺序没有重复

我写了一个脚本来打印出彩票组合.我的目标是:在1-49之间的彩票中有6个数字意味着有13,983,816种组合.我想在IN ORDER打印出所有组合,同时确保没有重复.

到目前为止,这是我的代码:

import random
numbers = []
for i in range(2):
    for j in range(6):
        numbers.append(random.randint(1,49))
        for k in range(j):
            while numbers[j]==numbers[k]:
                numbers[j]=random.randint(1,49)
    print sorted(numbers)
    numbers = []
f = open('combinations.txt', 'w')
f.write(str(sorted(numbers)))
Run Code Online (Sandbox Code Playgroud)

问题是:

终端的输出是:

[18, 20, 27, 32, 44, 48]
[5, 7, 10, 13, 33, 45]
Run Code Online (Sandbox Code Playgroud)

我想从头开始[1,2,3,4,5,6]并最终结束[44,45,46,47,48,49].所以我需要订购结果.

此外,我已经尝试将列表转换为字符串,因此我可以将结果放在一个大文本文件中,但我现在只是打印[]到文本文件.

python

0
推荐指数
2
解决办法
4538
查看次数

如何筛选子列表列表

所以我有一个列表列表,我想删除不符合要求的子列表.

lst = [[57], [71], [87], [97], [99], [101], [103], [113], [114], [115], [128], [131], [137], [147], [156], [163], [186]]
spectrum = [0, 113, 128, 186, 241, 299, 314, 427]
Run Code Online (Sandbox Code Playgroud)

我试过的代码和结果:

for sublist in lst:  
    if sum(sublist) not in spectrum:  
        sublist.pop()

>>> [[], [], [], [], [], [], [], [113], [], [], [128], [], [], [], [], [], [186]]  
Run Code Online (Sandbox Code Playgroud)

子列表是否包含方括号?那么为什么当我弹出子列表时,括号仍然存在?我怎么解决这个问题?我也试过,lst.pop(sublist)但它保留了一些不符合要求的子列表.

python list

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

标签 统计

python ×8

dictionary ×2

list ×2

python-3.x ×2

c++ ×1

class ×1

file ×1

function ×1

iterator ×1

oop ×1

pyqt4 ×1

range ×1

regex ×1

sorting ×1

split ×1

vector ×1