Create a new tuple with one changed item

(I work interactively with a WordprocessingDocument object in IronPython using the OpenXML SDK, but this is really a general Python question that should be applied in all implementations)

I am trying to clear some tables from multiple Word documents. For each table, I have an iterator that gives me table row objects. Then I use the following generator instruction to get tuples of cells from each row:

for row in rows:
    t = tuple([c.InnerText for c in row.Descendants[TableCell]()])

Each tuple contains 4 elements. Now, in the column t[1]for each tuple, I need to apply a regular expression to the data. I know that tuples are immutable, so I'm glad to either create a new tuple, or build a tuple in a different way. Given an row.Descendants[TableCell]()iterator returns, what is the most Pythonic (or at least the easiest) way to build a tuple from an iterator, where do I want to change the returned nth element ?

Now my brute force method is to create a tuple from the left slice ( t[:n-1]), the modified data in t[n]and the right slice ( t[n+1:]), but I feel like the module itertoolsshould have something to help me here.

+3
source share
4
def item(i, v):
  if i != 1: return v
  return strangestuff(v)

for row in rows:
  t = tuple(item(i, c.InnerText)
            for i, c in enumerate(row.Descendants[TableCell]())
           )
+6

:

temp_list = [c.InnerText for c in row.Descendants[TableCell]()]
temp_list[2] = "Something different"
t = tuple(temp_list)

:

>>> temp_list = [i for i in range(4)]
>>> temp_list[2] = "Something different"
>>> t = tuple(temp_list)
>>> t
(0, 1, 'Something different', 3)
+2

If each set contains 4 elements, then, frankly, I think it would be better for you to assign them to separate variables, manipulate them, and then build your tuple:

for row in rows:
    t1, t2, t3, t4 = tuple([c.InnerText for c in row.Descendants[TableCell]()])
    t1 = ...
    t = (t1, t2, t3, t4)
+1
source

What I did at all, but I'm not a fan:

l = list (oldtuple) l [2] = foo t = tuple (l)

I need something like update () for dicts

newtuple = update (oldtuple, (None, None, val, None))

Or maybe the right structure is zip

newtuple = update (oldtuple, ((2, val), (3, val)))

0
source

Source: https://habr.com/ru/post/1723682/


All Articles