namedtuple

Python: Copying named tuples with same attributes / fields

为君一笑 提交于 2019-12-10 17:22:58
问题 I am writing a function that takes a named tuple and must return a super set of that tuple. For example if I was to receive a named tuple like this: Person(name='Bob', age=30, gender='male') I want to return a tuple that looks like this: Person(name='Bob', age=30, gender='male', x=0) Currently I am doing this: tuple_fields = other_tuple[0]._fields tuple_fields = tuple_fields + ('x') new_tuple = namedtuple('new_tuple', tuple_fields) Which is fine, but I do not want to have to copy each field

namedtuple — applications of different type names in the same definition

≯℡__Kan透↙ 提交于 2019-12-10 16:45:57
问题 The Python namedtuple factory function allows the name of the subclass it creates to be specified twice — first on the left side of the declaration and then as the first argument of the function (IPython 1.0.0, Python 3.3.1): In [1]: from collections import namedtuple In [2]: TypeName = namedtuple('OtherTypeName', ['item']) All the examples I've seen on the docs.python.org site use an identical name in both positions. But it's possible to use different names, and they function differently: In

Python: Using namedtuple._replace with a variable as a fieldname

让人想犯罪 __ 提交于 2019-12-10 13:00:06
问题 Can I reference a namedtuple fieldame using a variable? from collections import namedtuple import random Prize = namedtuple("Prize", ["left", "right"]) this_prize = Prize("FirstPrize", "SecondPrize") if random.random() > .5: choice = "left" else: choice = "right" #retrieve the value of "left" or "right" depending on the choice print "You won", getattr(this_prize,choice) #replace the value of "left" or "right" depending on the choice this_prize._replace(choice = "Yay") #this doesn't work print

PySpark flatmap should return tuples with typed values

蹲街弑〆低调 提交于 2019-12-10 12:18:34
问题 I'm using Jupyter Notebook with PySpark. Within that I have a have a dataframe that has a schema with column names and types (integer, ...) for those columns. Now I use methods like flatMap but this returns a list of tuples that have no fixed type anymore. Is there a way to achieve that? df.printSchema() root |-- name: string (nullable = true) |-- ... |-- ... |-- ratings: integer (nullable = true) Then I use flatMap to do some calculations with the rating values (obfuscated here): df.flatMap

Structure accessible by attribute name or index options

独自空忆成欢 提交于 2019-12-10 03:45:57
问题 I am very new to Python, and trying to figure out how to create an object that has values that are accessible either by attribute name, or by index. For example, the way os.stat() returns a stat_result or pwd.getpwnam() returns a struct_passwd. In trying to figure it out, I've only come across C implementations of the above types. Nothing specifically in Python. What is the Python native way to create this kind of object? I apologize if this has been widely covered already. In searching for

Serializing a nested namedtuple into JSON with Python >= 2.7

寵の児 提交于 2019-12-10 02:41:50
问题 I have a problem similar to CalvinKrishy's problem Samplebias's solution is not working with the data I have. I am using Python 2.7. Here's the data: Namedtuple >>> a_t = namedtuple('a','f1 words') >>> word_t = namedtuple('word','f2 value') >>> w1 = word_t(f2=[0,1,2], value='abc') >>> w2 = word_t(f2=[3,4], value='def') >>> a1 = a_t(f1=[0,1,2,3,4],words=[w1, w2]) >>> a1 a(f1=[0, 1, 2, 3, 4], words=[word(f2=[0, 1, 2], value='abc'), word(f2=[3, 4], value='def')]) Dict >>> w3 = {} >>> w3['f2'] =

Pretty print namedtuple

孤者浪人 提交于 2019-12-10 01:04:50
问题 I tried pprint from pprint , but its output is just one line, there is no multiline output and no indentation. 回答1: I use the builtin function vars to get the namedtuple as a dictionary. However, it returns an OrderedDict which pprint won't indent, so I convert it to a dict : >>> from collections import namedtuple >>> Busbar = namedtuple('Busbar', 'id name voltage') >>> busbar = Busbar(id=102, name='FACTORY', voltage=21.8) With pprint and dict : >>> from pprint import pprint >>> pprint(dict

Looping over elements of named tuple in python

牧云@^-^@ 提交于 2019-12-09 14:27:04
问题 I have a named tuple which I assign values to like this: class test(object): self.CFTs = collections.namedtuple('CFTs', 'c4annual c4perren c3perren ntfixing') self.CFTs.c4annual = numpy.zeros(shape=(self.yshape, self.xshape)) self.CFTs.c4perren = numpy.zeros(shape=(self.yshape, self.xshape)) self.CFTs.c3perren = numpy.zeros(shape=(self.yshape, self.xshape)) self.CFTs.ntfixing = numpy.zeros(shape=(self.yshape, self.xshape)) Is there a way to loop over elements of named tuple? I tried doing

extend Python namedtuple with many @properties?

不问归期 提交于 2019-12-09 04:42:46
问题 How can namedtuples be extended or subclassed with many additional @properties ? For a few, one can just write the text below; but there are many, so I'm looking for a generator or property factory. One way would be to generate text from _fields and exec it; another would be an add_fields with the same effect at runtime. (My @props are to get rows and fields in a database scattered across several tables, so that rec.pname is persontable[rec.personid].pname ; but namedtuples-with-smart-fields

Python how to edit data in a namedtuple stored in a list?

*爱你&永不变心* 提交于 2019-12-08 08:59:43
问题 import struct from collections import namedtuple StructPageNum = namedtuple('FDResult', ['DeviceID', 'PageNum','PicSize','PicData']) PageNumList = [] Node = StructPageNum(DeviceID='NR09', PageNum=[],PicSize=100,PicData='') PageNumList.append(Node) PageNumList[0].PicData = 'hello' //how to do at here? QUESTION how to edit the value of PicData? 回答1: It looks to me like you can use the _replace method of a namedtuple to do this pretty easily: PageNumList[0] = PageNumList[0]._replace(PicData=