简体   繁体   中英

Finding and replacing element in Python

I am new to the python programming and wanted to know how can I iterate over elements below then replace strings and make my data list look like below. Thank you in advance.

[{u 'name': u 'xxx',
u 'data': [
    [u 'last_00_10', x],
    [u 'last_11_20', x],
    [u 'last_21_30', x],
],
u 'id': x }]

After replacing string, I want it to look like below

[{u 'name': u 'xxx',
u 'data': [
    [u '0-10 Days', x],
    [u '11-20 Days', x],
    [u '21-30 Days', x],
],
u 'id': x }] 

You have a list which contains a dictionary. The 'data' key in the dictionary contains a list. You want to iterate over that list and replace the first item in the list with different text.

x = 1
your_data = [{u'name': u'xxx',
u'data': [
    [u'last_00_10', x],
    [u'last_11_20', x],
    [u'last_21_30', x],
],
u'id': x }]

for item in your_data[0]['data']:
    item_split = item[0].split('_')
    item[0] = str(int(item_split[1])) + '-' + str(int(item_split[2])) + ' Days'

print(your_data)

This gives:

[{'id': 1, 'name': 'xxx', 'data': [['00-10 Days', 1], ['11-20 Days', 1], ['21-30 Days', 1]]}]

first, why you put 1 dict on a list? you'll put other dicts inside?, but I'll use your structure.. you can do something like this(I named your list L): and x = "" to work..(it's a non defined yet variable..

x = ""


L = [
        {
            u'name': u'xxx',
            u'data': [
                        [u'last_00_10', x],
                        [u'last_11_20', x],
                        [u'last_21_30', x],
                    ],
            u'id': x 
        }
]

newData = [u"0-10 Days", u'11-20 Days', u'21-30 Days']
for i in range(len( L[0][u'data'] )):
    L[0][u'data'][i][0] = newData[i]

it'll work as you want..

I corrected the spaces between u'string' on the code

This almost give what you want:

import re

x = 42
stuff = [{u'name': u'xxx',
          u'data': [
         [u'last_00_10', x],
         [u'last_11_20', x],
         [u'last_21_30', x],
                   ],
          u'id': x }]

for row in stuff[0]['data']:
    row[0] = re.sub(r'last_(\d+)_(\d+)',
                    r'\1-\2 Days', row[0])
    print(row)

Gives:

['00-10 Days', 42]
['11-20 Days', 42]
['21-30 Days', 42]

If you want single digit numbers ("00" to "0") there is a bit more work.

def subit(m):
    f1, f2 = m.groups()[:2]
    return "%d-%d Days" % (int(f1), int(f2))

for row in stuff[0]['data']:
    row[0] = re.sub(r'last_(\d+)_(\d+)', subit, row[0])
    print(row)

Gives:

['0-10 Days', 42]
['11-20 Days', 42]
['21-30 Days', 42]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM