python-2.x

Assign external function to class variable in Python

这一生的挚爱 提交于 2019-12-22 01:53:59
问题 I am trying to assign a function defined elsewhere to a class variable so I can later call it in one of the methods of the instance, like this: from module import my_func class Bar(object): func = my_func def run(self): self.func() # Runs my function The problem is that this fails because when doing self.func() , then the instance is passed as the first parameter. I've come up with a hack but seems ugly to me, anybody has an alternative? In [1]: class Foo(object): ...: func = lambda *args:

Difference between io.open vs open in python

狂风中的少年 提交于 2019-12-21 06:50:11
问题 In the past, there's codecs which got replaced by io . Although it seems like it's more advisable to use io.open , most introductory python classes still teaches open . There's a question with Difference between open and codecs.open in Python but is open a mere duck-type of io.open ? If not, why is it better to use io.open ? And why is it easier to teach with open ? In this post (http://code.activestate.com/lists/python-list/681909/), Steven DAprano says that the built in open is using the io

Reading russian language data from csv

依然范特西╮ 提交于 2019-12-21 06:06:20
问题 I have some data in CSV file that are in Russian: 2-комнатная квартира РДТ', мкр Тастак-3, Аносова — Толе би;Алматы 2-комнатная квартира БГР', мкр Таугуль, Дулати (Навои) — Токтабаева;Алматы 2-комнатная квартира ЦФМ', мкр Тастак-2, Тлендиева — Райымбека;Алматы Delimiter is ; symbol. I want to read data and put it into array. I tried to read this data using this code: def loadCsv(filename): lines = csv.reader(open(filename, "rb"),delimiter=";" ) dataset = list(lines) for i in range(len(dataset

2d dictionary with many keys that will return the same value

守給你的承諾、 提交于 2019-12-21 06:02:15
问题 I want to make a 2d dictionary with multiple keys per value. I do not want to make a tuple a key. But rather make many keys that will return the same value. I know how to make a 2d dictionary using defaultdict: from collections import defaultdict a_dict = defaultdict(dict) a_dict['canned_food']['spam'] = 'delicious' And I can make a tuple a key using a_dict['food','canned_food']['spam'] = 'delicious' But this does not allow me to do something like print a_dict['canned_food]['spam'] Because

Elegant way to remove contiguous repeated elements in a list?

不打扰是莪最后的温柔 提交于 2019-12-21 05:19:17
问题 I'm looking for a clean, Pythonic, way to eliminate from the following list: li = [0, 1, 2, 3, 3, 4, 3, 2, 2, 2, 1, 0, 0] all contiguous repeated elements (runs longer than one number) so as to obtain: re = [0, 1, 2, 4, 3, 1] but although I have working code, it feels un-Pythonic and I am quite sure there must be a way out there (maybe some lesser known itertools functions?) to achieve what I want in a far more concise and elegant way. 回答1: Here is a version based on Karl's which doesn't

How to import a csv-file into a data array?

混江龙づ霸主 提交于 2019-12-21 04:04:26
问题 I have a line of code in a script that imports data from a text file with lots of spaces between values into an array for use later. textfile = open('file.txt') data = [] for line in textfile: row_data = line.strip("\n").split() for i, item in enumerate(row_data): try: row_data[i] = float(item) except ValueError: pass data.append(row_data) I need to change this from a text file to a csv file. I don't want to just change this text to split on commas (since some values can have commas if they

Watchdog getting events thrice in Python 3

那年仲夏 提交于 2019-12-20 21:40:15
问题 I'm creating a program in Python using Watchdog that watches a set of files and takes actions based on changes. I put the exact example from their site in a file: import sys import time import logging from watchdog.observers import Observer from watchdog.events import LoggingEventHandler if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') path = sys.argv[1] if len(sys.argv) > 1 else '.' event_handler =

Watchdog getting events thrice in Python 3

懵懂的女人 提交于 2019-12-20 21:40:01
问题 I'm creating a program in Python using Watchdog that watches a set of files and takes actions based on changes. I put the exact example from their site in a file: import sys import time import logging from watchdog.observers import Observer from watchdog.events import LoggingEventHandler if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') path = sys.argv[1] if len(sys.argv) > 1 else '.' event_handler =

Python ConfigParser interpolation from foreign section

白昼怎懂夜的黑 提交于 2019-12-20 17:38:57
问题 With Python ConfigParser, is it possible to use interpolation across foreign sections? My mind seems to tell me I've seen that it's possible somewhere, but I can't find it when searching. This example doesn't work, but it's to give an idea of what I'm trying to do. [section1] root = /usr [section2] root = /usr/local [section3] dir1 = $(section1:root)/bin dir2 = $(section2:root)/bin Note that I'm using Python 2.4. 回答1: In python 3.2 and up this is perfectly valid: [Common] home_dir: /Users

What does “print >>” do in python? [duplicate]

妖精的绣舞 提交于 2019-12-20 11:04:14
问题 This question already has an answer here : How does the right-shift operator work in a python print statement? (1 answer) Closed 4 years ago . I have to translate a code from python 2 into python 3 and I can't understand what does print >> do and how should I write it in python 3. print >> sys.stderr, '--' print >> sys.stderr, 'entrada1: ', entrada1 print >> sys.stderr, 'entrada2: ', entrada2 print >> sys.stderr, '--' 回答1: The >> sys.stderr part makes the print statement output to stderr