Search Results

Search found 14486 results on 580 pages for 'python idle'.

Page 174/580 | < Previous Page | 170 171 172 173 174 175 176 177 178 179 180 181  | Next Page >

  • change values in a list - python

    - by ariel
    I have this code: a=[['a','b','c'],['a','f','c'],['a','c','d']] for x in a: for y in x: if 'a' in x: x.replace('a','*')` but the result is: a=[['a','b','c'],['a','f','c'],['a','c','d']] and bot a=[['b','c'],['f','c'],['c','d']] What should I do so the changes will last?

    Read the article

  • Testing variable types in Python

    - by Jasper
    Hello, I'm creating an initialising function for the class 'Room', and found that the program wouldn't accept the tests I was doing on the input variables. Why is this? def __init__(self, code, name, type, size, description, objects, exits): self.code = code self.name = name self.type = type self.size = size self.description = description self.objects = objects self.exits = exits #Check for input errors: if type(self.code) != type(str()): print 'Error found in module rooms.py!' print 'Error number: 110' elif type(self.name) != type(str()): print 'Error found in module rooms.py!' print 'Error number: 111' elif type(self.type) != type(str()): print 'Error found in module rooms.py!' print 'Error number: 112' elif type(self.size) != type(int()): print 'Error found in module rooms.py!' print 'Error number: 113' elif type(self.description) != type(str()): print 'Error found in module rooms.py!' print 'Error number: 114' elif type(self.objects) != type(list()): print 'Error found in module rooms.py!' print 'Error number: 115' elif type(self.exits) != type(tuple()): print 'Error found in module rooms.py!' print 'Error number: 116' When I run this I get this error: Traceback (most recent call last): File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/rooms.py", line 148, in <module> myRoom = Room(101, 'myRoom', 'Basic Room', 5, '<insert description>', myObjects, myExits) File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/rooms.py", line 29, in __init__ if type(self.code) != type(str()): TypeError: 'str' object is not callable

    Read the article

  • Python script not working when run from browser directly

    - by splatterdash
    I'm trying to run this script: import re, os def build_pool(cwd): global xtn_pool, file_pool xtn, xtn_pool = re.compile('\\.[0-9a-zA-Z]{1,4}$'), [] file_pool = [files for files in os.listdir(cwd) if os.path.isfile(files) and xtn.search(files)] # Lists all the file extension in the folder for file in file_pool: if not xtn_pool.__contains__(xtn.search(file).group()): xtn_pool.append(xtn.search(file).group()) return xtn_pool.sort(), file_pool if __name__ == '__main__': import sys #if path is given, change working directory to path if len(sys.argv) >= 2: os.chdir(sys.argv[1]) build_pool(os.getcwd()) #if no path is given when running, do renaming in current folder else: build_pool(os.getcwd()) print('The folder contains the following extensions: ') for i in range(0, len(xtn_pool)): print(repr(i+1) + '. ' + xtn_pool[i][1:]) opt = int(input('Which one would you like to replace? ')) xtn_pick = xtn_pool[opt-1] # Lists all the file with the chosen extension xtn_file_pool = [file for file in file_pool if file.endswith(xtn_pick)] print('There are {0} files with the {1} extension.'.format(len(xtn_file_pool), xtn_pick)) xtn_new = input('Input replacement extension: ') # The actual renaming process for file in xtn_file_pool: os.rename(file, file[:-len(xtn_pick)+1] + xtn_new) directly from my file browser (Nautilus), but for some reason it's not working. When I run it from terminal (python3 scriptname.py) it works fine as intended. But when I just click the script file in Nautilus, choose 'Run in Terminal', it always stops after asking 'Input replacement extension: '. How can I make this script run without using the terminal?

    Read the article

  • Serialize the @property methods in a Python class.

    - by ashchristopher
    Is there a way to have any @property definitions passed through to a json serializer when serializing a Django model class? example: class FooBar(object.Model) name = models.CharField(...) @property def foo(self): return "My name is %s" %self.name Want to serialize to: [{ 'name' : 'Test User', 'foo' : 'My name is Test User', },]

    Read the article

  • Python: How to transfer varrying length arrays over a network connection

    - by Devin
    Hi, I need to transfer an array of varying length in which each element is a tuple of two integers. As an example: path = [(1,1),(1,2)] path = [(1,1),(1,2),(2,2)] I am trying to use pack and unpack, however, since the array is of varying length I don't know how to create a format such that both know the format. I was trying to turn it into a single string with delimiters, such as: msg = 1&1~1&2~ sendMsg = pack("s",msg) or sendMsg = pack("s",str(msg)) on the receiving side: path = unpack("s",msg) but that just prints 1 in this case. I was also trying to send 4 integers as well, which send and receive fine, so long as I don't include the extra string representing the path. sendMsg = pack("hhhh",p.direction[0],p.direction[1],p.id,p.health) on the receive side: x,y,id,health = unpack("hhhh",msg) The first was for illustration as I was trying to send the format "hhhhs", but either way the path doesn't come through properly. Thank-you for your help. I will also be looking at sending a 2D array of ints, but I can't seem to figure out how to send these more 'complex' structures across the network. Thank-you for your help.

    Read the article

  • Python - alternative to list.remove(x)?

    - by Seafoid
    Hi, I wish to compare two lists. Generally this is not a problem as I usually use a nested for loop and append the intersection to a new list. In this case, I need to delete the intersection of A and B from A. A = [['ab', 'cd', 'ef', '0', '567'], ['ghy5'], ['pop', 'eye']] B = [['ab'], ['hi'], ['op'], ['ej']] My objective is to compare A and B and delete A intersection B from A, i.e., delete A[0][0] in this case. I tried: def match(): for i in A: for j in i: for k in B: for v in k: if j == v: A.remove(j) list.remove(x) throws a ValueError.

    Read the article

  • regex in python, can this be improved upon?

    - by tipu
    I have this piece of code that finds words that begin with @ or #, p = re.findall(r'@\w+|#\w+', str) Now what irks me about this is repeating \w+. I am sure there is a way to do something like p = re.findall(r'(@|#)\w+', str) That will produce the same result but it doesn't, it instead returns only # and @. How can that regex be changed so that I am not repeating the \w+? This code comes close, p = re.findall(r'((@|#)\w+)', str) But it returns [('@many', '@'), ('@this', '@'), ('#tweet', '#')] (notice the extra '@', '@', and '#'.

    Read the article

  • Importing data from a text file using python

    - by Will
    I have a text file containing data in rows and columns (~17000 rows in total). Each column is a uniform number of characters long, with the 'unused' characters filled in by spaces. For example, the first column is 11 characters long, but the last four characters in that column are always spaces (so that it appears to be a nice column when viewed with a text editor). Sometimes it's more than four if the entry is less than 7 characters. The columns are not otherwise separated by commas, tabs, or spaces. They are also not all the same number of characters (the first two are 11, the next two are 8 and the last one is 5 - but again, some are spaces). What I want to do is import the entires (which are numbers) in the last two columns if the second column contains the string 'OW' somewhere in it. Any help would be greatly appreciated.

    Read the article

  • undo or reverse argsort(), python

    - by Vincent
    Given an array 'a' I would like to sort the array by columns "a.sort(axis=0)" do some stuff to the array and then undo the sort. By that I don't mean re sort but basically reversing how each element was moved. I assume argsort() is what I need but it is not clear to me how to sort an array with the results of argsort() or more importantly apply the reverse/inverse of argsort() Here is a little more detail I have an array a, shape(a) = rXc I need to sort each column aargsort = a.argsort(axis=0) # May use this later aSort = a.sort(axis=0) now average each row aSortRM = asort.mean(axis=1) now replace each col in a row with the row mean. is there a better way than this aWithMeans = ones_like(a) for ind in range(r) # r = number of rows aWithMeans[ind]* aSortRM[ind] Now I need to undo the sort I did in the first step. ????

    Read the article

  • How do you create a daemon in Python?

    - by DavidM
    Searching on Google reveals x2 code snippets. The first result is to this code recipe which has a lot of documentation and explanation, along with some useful discussion underneath. However, another code sample, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc. These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?

    Read the article

  • Overriding Built-in Classes (Python)

    - by Yipeng
    How can I view and override the full definition for built in classes? I have seen the library docs but am looking for something more. For e.g. is it possible to override the Array Class such that the base index starts from 1 instead of 0, or to override .sort() of list to a sorting algorithm of my own liking?

    Read the article

  • merging indexed array in Python

    - by leon
    Suppose that I have two numpy arrays of the form x = [[1,2] [2,4] [3,6] [4,NaN] [5,10]] y = [[0,-5] [1,0] [2,5] [5,20] [6,25]] is there an efficient way to merge them such that I have xmy = [[0, NaN, -5 ] [1, 2, 0 ] [2, 4, 5 ] [3, 6, NaN] [4, NaN, NaN] [5, 10, 20 ] [6, NaN, 25 ] I can implement a simple function using search to find the index but this is not elegant and potentially inefficient for a lot of arrays and large dimensions. Any pointer is appreciated.

    Read the article

  • Python lxml - returns null list

    - by Chris Finlayson
    I cannot figure out what is wrong with the XPATH when trying to extract a value from a webpage table. The method seems correct as I can extract the page title and other attributes, but I cannot extract the third value, it always returns an empty list? from lxml import html import requests test_url = 'SC312226' page = ('https://www.opencompany.co.uk/company/'+test_url) print 'Now searching URL: '+page data = requests.get(page) tree = html.fromstring(data.text) print tree.xpath('//title/text()') # Get page title print tree.xpath('//a/@href') # Get href attribute of all links print tree.xpath('//*[@id="financial"]/table/tbody/tr/td[1]/table/tbody/tr[2]/td[1]/div[2]/text()') Unless i'm missing something, it would appear the XPATH is correct: Chrome screenshot I checked Chrome console, appears ok! So i'm at a loss $x ('//*[@id="financial"]/table/tbody/tr/td[1]/table/tbody/tr[2]/td[1]/div[2]/text()') [ "£432,272" ]

    Read the article

  • deleting unaccessed files using python

    - by damon
    My django app parses some files uploaded by the user.It is possible that the file uploaded by the user may remain in the server for a long time ,without it being parsed by the app.This can increase in size if a lot of users upload a lot of files. I need to delete those files not recently parsed by the app -say not accessed for last 24 hours.I tried like this import os import time dirname = MEDIA_ROOT+my_folder filenames = os.listdir(dirname) filenames = [os.path.join(dirname,filename) for filename in filenames] for filename in filenames: last_access = os.stat(filename).st_atime #secs since epoch rtime = time.asctime(time.localtime(last_access)) print filename+'----'+rtime This shows the last accessed times for each file..But I am not sure how I can test if the file access time was within the last 24 hours..Can somebody help me out?

    Read the article

  • Efficient way to access a mapping of identifiers in Python

    - by sixbelo
    I am writing an app to do a file conversion and part of that is replacing old account numbers with a new account numbers. Right now I have a CSV file mapping the old and new account numbers with around 30K records. I read this in and store it as dict and when writing the new file grab the new account from the dict by key. My question is what is the best way to do this if the CSV file increases to 100K+ records? Would it be more efficient to convert the account mappings from a CSV to a sqlite database rather than storing them as a dict in memory?

    Read the article

  • most widely used python web app deployment style

    - by mete
    I wonder which option is more stable (leaving performance aside) and is more widely used (I assume the widely used one is the most stable): apache - mod_wsgi apache - mod_fcgid apache - mod_proxy_ajp apache - mod_proxy_http for a project that will serve REST services with small json formatted input and output messages and web pages, up to 100 req/s. Please comment on apache if you think nginx etc. is more suitable. Thanks.

    Read the article

  • Skip subdirectory in python import

    - by jstaab
    Ok, so I'm trying to change this: app/ - lib.py - models.py - blah.py Into this: app/ - __init__.py - lib.py - models/ - __init__.py - user.py - account.py - banana.py - blah.py And still be able to import my models using from app.models import User rather than having to change it to from app.models.user import User all over the place. Basically, I want everything to treat the package as a single module, but be able to navigate the code in separate files for development ease. The reason I can't do something like add for file in __all__: from file import * into init.py is I have circular references between the model files. A fix I don't want is to import those models from within the functions that use them. But that's super ugly. Let me give you an example: user.py ... from app.models import Banana ... banana.py ... from app.models import User ... I wrote a quick pre-processing script that grabs all the files, re-writes them to put imports at the top, and puts it into models.py, but that's hardly an improvement, since now my stack traces don't show the line number I actually need to change. Any ideas? I always though init was probably magical but now that I dig into it, I can't find anything that lets me provide myself this really simple convenience.

    Read the article

  • Object for storing strings in Python

    - by evg
    class MyWriter: def __init__(self, stdout): self.stdout = stdout self.dumps = [] def write(self, text): self.stdout.write(smart_unicode(text).encode('cp1251')) self.dumps.append(text) def close(self): self.stdout.close() writer = MyWriter(sys.stdout) save = sys.stdout sys.stdout = writer I use self.dumps list to store data obtained from prints. Is there a more convenient object for storing string lines in memory? Ideally I want dump it to one big string. I can get it like this "\n".join(self.dumps) from code above. May be it's better to just concatenate strings - self.dumps += text?

    Read the article

< Previous Page | 170 171 172 173 174 175 176 177 178 179 180 181  | Next Page >