Ad

Python: Every N Of List Of List Replace New List

- 1 answer

My curent list looks like this in csv file:

4IMWQ;1PLZT;AYNQV;NRTF7;T4AXP
4SCUM;3EYFC;6MT9H;R2Z9Y;N91K1
H8EF1;JO4HZ;MJTOF;KMFPP;925EF
9VYY1;4FG81;VI4US;79R6F;7804A
29GHY;U47WA;VY6SF;WRSLS;HPAU5
TKEA0;6ST9T;JYD4B;5A55Y;NZKVN

But i need to replace evey nth of list to numeric value. If i use this method i end up with wrong solution and lists aint same lenght anymore.

char = 5
rows = 50
cols = 5
def id_generator(size= char, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))
def nr_generator(size= char, chars=string.octdigits):
    return ''.join(random.choice(chars) for x in range(size))
nums = 3
data = []
nums1 = nums - 1
for i in range(rows):
    sublist = []
    for y in range(cols):
        sublist.append(id_generator())   
    data.append(sublist)
data[nums1::nums] = [[nr_generator()] for x in data[nums1::nums]]

>>>[['UOL9P', 'TAZI6', 'NIYRK', 'V8Z1B', 'PCFK8'], 
>>>['IHBV2', 'UULQK', '88J9L', 'AEBP6', '656U9'], 
>>>['66257'], 
>>>['ST2P2', 'FO1VT', '583CM', 'GQY1Q', '3BBRC']
>>>['RQCKB', 'X2A6W', 'XMNM7', '16OP1', '4VYMZ'], 
>>>['45024']...]

Should look like:

>>>[['UOL9P', 'TAZI6', 'NIYRK', 'V8Z1B', 'PCFK8'], 
>>>['IHBV2', 'UULQK', '88J9L', 'AEBP6', '656U9'], 
>>>['66257', '58478', '87415', '58446', '87115'], 
>>>['ST2P2', 'FO1VT', '583CM', 'GQY1Q', '3BBRC']
>>>['RQCKB', 'X2A6W', 'XMNM7', '16OP1', '4VYMZ'], 
>>>['45024', '14587', '58461', '54786', '98524']...]
Ad

Answer

You can do this in a list comprehension. Select which generator to use based on the row number:

nums  = 3
nums1 = nums - 1
data  = [ [ nr_generator() if r%nums==nums-1 else id_generator()     
            for _ in range(cols) ]
         for r in range(rows*cols)]

print(*data,sep='\n')

['HN7VD', 'Z57K3', 'L6F5O', 'VU77R', 'V6ANV']
['5A9SG', 'OJGNH', 'XPWHA', 'VWECX', 'PCO3A']
['03751', '50217', '63143', '27251', '73064']
['1YMYT', 'DLQ21', '8ZXY0', 'KEJF8', 'AV040']
['QGEHO', 'DNNYO', 'QNMDU', '5VDF1', '2GIF3']
['50435', '41373', '60173', '65517', '71325']
['92KS3', 'ZVRPK', '8VURD', 'KKHU5', 'U28LL']
['QOYSM', 'UB9Q2', 'VYC6J', 'ADUJL', 'FXC8I']
['26041', '37426', '13752', '76574', '65502']
['0TQOH', 'VBN77', 'QG3VV', 'WWWDO', 'PF5BN']
...

You could make is a bit more concise by playing with a list of generator functions corresponding to the cycle of rows.

nums  = 3
gens  = [id_generator]*(nums-1)+[nr_generator]
data  = [[gens[r%nums]() for _ in range(cols)] for r in range(rows*cols)]
Ad
source: stackoverflow.com
Ad