How to modify values in a list of lists based on a sub-value

python list of lists
create list of lists python
nested list python
python enumerate
accessing list of lists python
python find max value in list of lists
list comprehension || python
create nested list python

I have a great challenge trying to resolve this. I have this list of lists:

[['060710080013011', 9],
 ['060710080013011', 9],
 ['060710080013011', 9],
 ['060710080013011', 9],
 ['060710080013011', 9],
 ['060710080013011', 9],
 ['060710080013011', 9],
 ['060710080013011', 9],
 ['060710080013011', 9],
 ['060710080013033', 8],
 ['060710080013033', 8],
 ['060710080013033', 8],
 ['060710080013033', 8],
 ['060710080013033', 8],
 ['060710080013033', 8],
 ['060710080013033', 8],
 ['060710080013033', 8],
 ['060710080021000', 15],
 ['060710080021000', 15],
 ['060710080021000', 15],
 ['060710080021000', 15],
 ['060710080021000', 15],
 ['060710080021000', 15],
 ['060710080021000', 15],
 ['060710080021000', 15],
 ['060710080021000', 15],
 ['060710080021000', 15],
 ['060710080021000', 15],
 ['060710080021000', 15],
 ['060710080021000', 15],
 ['060710080021000', 15],
 ['060710080021000', 15]]

The first value is an ID and the second value is how many times this ID is appearing on the list of lists. The problem is the following:

When the second value is greater than 7, I need to change the values in every second item in each tuple, here the desired output:

[['060710080013011', 7],
 ['060710080013011', 7],
 ['060710080013011', 7],
 ['060710080013011', 7],
 ['060710080013011', 7],
 ['060710080013011', 7],
 ['060710080013011', 7],
 ['060710080013011_2', 2],
 ['060710080013011_2', 2],
 ['060710080013033', 7],
 ['060710080013033', 7],
 ['060710080013033', 7],
 ['060710080013033', 7],
 ['060710080013033', 7],
 ['060710080013033', 7],
 ['060710080013033', 7],
 ['060710080013033_2', 1],
 ['060710080021000', 7],
 ['060710080021000', 7],
 ['060710080021000', 7],
 ['060710080021000', 7],
 ['060710080021000', 7],
 ['060710080021000', 7],
 ['060710080021000', 7],
 ['060710080021000_2', 7],
 ['060710080021000_2', 7],
 ['060710080021000_2', 7],
 ['060710080021000_2', 7],
 ['060710080021000_2', 7],
 ['060710080021000_2', 7],
 ['060710080021000_2', 7],
 ['060710080021000_3', 1]]

If you see my desire output above I need to change the second item of every sublist that has a number greater than 7.

If you need clarification ask me, my first language is not English but I can do my best.

lista2 = [['100',9]]
for l in lista2:
    v = l[1] - 7
    c = 2
    while v > 0:
        l[1] = 7
        lista2.append([l[0]+"_"+str(c),min(v,7)])
        v -= 7
        c += 1

print(lista2)

should work as you have requested, mainly some syntax errors and misnamed variables in your code, please let me know if this does not work.

11. Lists, We have already seen that we can assign list values to variables or pass lists as the list, it is a good idea to use this value as the upper bound of a loop instead of a Although a list can contain another list, the nested list still counts as a single Unlike strings, lists are mutable, which means we can change their elements. Note that this creates a new list. If the list is too big or you don't want this for some other reason, you can use for i in xrange(len(a)): and then update a[i] if necessary. To get (index, value) pairs from a list, use enumerate(a) which returns an iterator yielding such pairs.

A naive solution will be to use groupby and a simple Counter, here's a working solution:

In [1]: from itertools import groupby

In [2]: from collections import Counter

In [3]: whatever = [['060710080013011', 9],  ['060710080013011', 9],  ['060710080013011', 9],  ['060710080013011', 9],  ['06071008001
   ...: 3011', 9],  ['060710080013011', 9],  ['060710080013011', 9],  ['060710080013011', 9],  ['060710080013011', 9],  ['06071008001
   ...: 3033', 8],  ['060710080013033', 8],  ['060710080013033', 8],  ['060710080013033', 8],  ['060710080013033', 8],  ['06071008001
   ...: 3033', 8],  ['060710080013033', 8],  ['060710080013033', 8],  ['060710080021000', 15],  ['060710080021000', 15],  ['060710080
   ...: 021000', 15],  ['060710080021000', 15],  ['060710080021000', 15],  ['060710080021000', 15],  ['060710080021000', 15],  ['0607
   ...: 10080021000', 15],  ['060710080021000', 15],  ['060710080021000', 15],  ['060710080021000', 15],  ['060710080021000', 15],  [
   ...: '060710080021000', 15],  ['060710080021000', 15],  ['060710080021000', 15]]

In [7]: counter = []
    ...: # we use groupby to group the inner list by key, i.e. the first label
    ...: for key, grouped in groupby(whatever, lambda x: x[0]):
    ...:     # here, we decide if we need to append the label if the item counts great than multiple of 7
    ...:     for idx, item in enumerate(grouped):
    ...:         # to get the LABEL_INDEX as new keyed
                 keyed = key if int(idx / 7) == 0 else "{}_{}".format(key, int(idx / 7) + 1)
    ...:         counter.append(keyed)
    ...: # simply use a counter to re-count the new label items
    ...: counted = Counter(counter)
    ...: answer = []
    ...: for keyed in sorted(counted):
    ...:     for _ in range(counted[keyed]):
    ...:         answer.append([keyed, counted[keyed]])
    ...:
    ...: print(answer)
    ...:
    ...:
    ...:
    ...:

[['060710080013011', 7], ['060710080013011', 7], ['060710080013011', 7], ['060710080013011', 7], ['060710080013011', 7], ['060710080013011', 7], ['060710080013011', 7], ['060710080013011_2', 2], ['060710080013011_2', 2], ['060710080013033', 7], ['060710080013033', 7], ['060710080013033', 7], ['060710080013033', 7], ['060710080013033', 7], ['060710080013033', 7], ['060710080013033', 7], ['060710080013033_2', 1], ['060710080021000', 7], ['060710080021000', 7], ['060710080021000', 7], ['060710080021000', 7], ['060710080021000', 7], ['060710080021000', 7], ['060710080021000', 7], ['060710080021000_2', 7], ['060710080021000_2', 7], ['060710080021000_2', 7], ['060710080021000_2', 7], ['060710080021000_2', 7], ['060710080021000_2', 7], ['060710080021000_2', 7], ['060710080021000_3', 1]]

Iterate over large list of lists and replace its elements, You're looping in incorrect order, take the advantage of the fact that dictionary provides O(1) lookups. So, you should loop over the list and  list = list.Where(w => w.Name == "height").Select(s => { s.Value = 30; return s; }).ToList(); NOTE: these 2 example are not the same! I repeat, the linq only returns 1 item (one row), and this is something I don't want, I need all items from the list as well (like foreach loop, it only do changes, but it does not remove any item).

# arr is the input( list of list)
output = []
n = len(arr)
i=0
while i<n:
    ID, f = arr[i]
    mul = 1
    while mul*7 < f:
        if mul!=1:
            newID = ID + '_' + str(mul)
        else:
            newID = ID
        temp = [[newID,7] for j in range(7)]
        mul += 1
        output += temp

    rem = f - ((mul-1)*7)
    newID = ID +  '_' + str(mul)
    temp = [[newID, rem] for j in range(rem)]
    output += temp

    i += f

print(output)

The code above gives the output as expected.

Python, Given list of lists in Python, write a Python program to find maximum value of list each Method #1: Using list comprehension. filter_none. edit close. play_arrow. link brightness_4 code. # Python code to Find maximum of list in nested list in another sublist · Python | Sort a list according to the second element in sublist  The problem in your initial approach was that your first list element is itself a list. Hence you cannot directly apply the ifelse logic as you would on an atomic vector. By using ?rapply you can avoid that problem (rapply is a recursive version of lapply).

My solution would look like this:

import pandas as pd
df = pd.DataFrame(lst)
df.columns = ['ID', 'counter']

df.counter = df.groupby('ID').cumcount() // 7

df.loc[df.counter>0, 'ID'] += '_' + (df.counter + 1)[df.counter>0].astype(str)
df.counter = df.applymap(lambda id: (df.ID==id).sum())['ID']

That's all - Finished.

In the following I'll explain every step:

To prepare your data for processing in pandas, load the library and put the data into a dataframe :

import pandas as pd
df = pd.DataFrame(lst)
df.columns = ['ID', 'counter']

Initially the counter is set to modulo 7 of the cumulative counter of the IDs in the dataset, which can be used for indexing subgroups of size seven:

df['counter'] = df.groupby('ID').cumcount() // 7

Now your dataset looks like this:

                 ID  counter
0   060710080013011        0
1   060710080013011        0
2   060710080013011        0
3   060710080013011        0
4   060710080013011        0
5   060710080013011        0
6   060710080013011        0
7   060710080013011        1
8   060710080013011        1
9   060710080013033        0
10  060710080013033        0
11  060710080013033        0
12  060710080013033        0
13  060710080013033        0
14  060710080013033        0
15  060710080013033        0
16  060710080013033        1
17  060710080021000        0
18  060710080021000        0
19  060710080021000        0
20  060710080021000        0
21  060710080021000        0
22  060710080021000        0
23  060710080021000        0
24  060710080021000        1
25  060710080021000        1
26  060710080021000        1
27  060710080021000        1
28  060710080021000        1
29  060710080021000        1
30  060710080021000        1
31  060710080021000        2 

Now change the IDs, i.e. only if counter>0 append "counter+1" as a string with a preceding underscore to the existing ID:

df.loc[df.counter>0, 'ID'] += '_' + (df.counter + 1)[df.counter>0].astype(str)

To change the counter back to the desired sum of IDs, apply a lambda function to each element which returns the sum over all occurences in the dataset of this element:

df.counter = df.applymap(lambda id: (df.ID==id).sum())['ID']

Then the dataset looks like this:

                   ID  counter
0     060710080013011        7      
1     060710080013011        7      
2     060710080013011        7      
3     060710080013011        7      
4     060710080013011        7      
5     060710080013011        7      
6     060710080013011        7      
7   060710080013011_2        2      
8   060710080013011_2        2      
9     060710080013033        7      
10    060710080013033        7      
11    060710080013033        7      
12    060710080013033        7      
13    060710080013033        7      
14    060710080013033        7      
15    060710080013033        7      
16  060710080013033_2        1      
17    060710080021000        7      
18    060710080021000        7      
19    060710080021000        7      
20    060710080021000        7      
21    060710080021000        7      
22    060710080021000        7      
23    060710080021000        7      
24  060710080021000_2        7      
25  060710080021000_2        7      
26  060710080021000_2        7      
27  060710080021000_2        7      
28  060710080021000_2        7      
29  060710080021000_2        7      
30  060710080021000_2        7      
31  060710080021000_3        1      

Python, Given a list of lists, write a Python program to find the list with maximum length. for loop to find length of each list and output the maximum length. filter_none. edit close Python | Find the sublist with maximum value in given nested list · Python column values in mixed length 2D List · Python | Sort a list according to the  Creating 3 Lists based on Data Validation. Here we will create two worksheets. In the first worksheet, we will insert the information of the task that we are going to perform. We will create a 3-dropdown list of dress, color, and size. The procedure is given below. In S3 create three lists of Dress, Color, and Size.

Python compare two lists of different length, The values stored in a tuple can be any type, and they are indexed by integers. Python Nested List Length Example. my images contain one black ring at the center and another image have not i At first sight, it might seem that lists can always replace tuples. Here, you're generally comparing the value of two objects. You can modify the content of a list as needed with Python. Modifying a list means to change a particular entry, add a new entry, or remove an existing entry. To perform these tasks, you must sometimes read an entry. The concept of modification is found within the acronym CRUD, which stands for Create, Read, Update, and Delete.

How to use Python's min() and max() with nested lists – dbader.org, Finding the minimum or maximum element of a list of lists based on a specific property of the But if we simply call min and max on that nested list we don't get the results we expected. How can we change the comparison behavior? Using get() to return a default value from a Python dict – Python's dictionaries have a  Learn how to create relationships between lists by using a combination of unique columns, lookup columns, and relationship enforcement (cascade and restrict delete) to preserve the integrity of your data; and to view, edit, and delete items and lists in list relationships.

Python: Check if a list or list of lists is empty or not – thispointer.com, Then we will also see how to check if a list of lists is empty or not using for Python provides a built-in function len(), If any of the sub list is non-empty then it returns False, where as if all sub lists are empty then it returns True check if all values in Numpy Array are zero (in both 1D & 2D arrays) - Python  Values lists in FileMaker Pro can also be designed so that the values themselves change or are updated when a value in another field is changed. This behavior is helpful to narrow down the size of a large value list or to only show the values that are applicable based on the value in another field or fields.

Comments
  • I'm a little confused about the change you are trying to make to the tuple. If i understand correctly, the second value in each tuple is a "count" of the ID, and this is the value you want to change if it exceeds 7, what do you want to change it to? in your result you have 3 values in the tuple instead of 2, are you adding this as well as changing the value of the 2nd item?
  • Could you explain your desired output a little? Give an example of actual input and what the desired output for that should be. That would help in clarifying the question.
  • if I am correct. [123456789, 9] you would want to be corrected to [123456789, 7], [123456789_2, 2] is this correct?
  • Thank you for you time @JamesLingham. Basically, if you si the input value, the first 9 sublists in the LIST have the same ID and as a second sub value, all this have 9. So basically I need to change the 9 for a 7 to the first 7 values and a 2 for the last 2. Does it make sense. please feel free to ask.
  • so creating a new ID for the last 2 occurrences? where does the 3rd value in the tuple come from? 155 etc, it seems to carry over to the new set of ID's too, but does not appear in your first list.
  • Thank you very much @James . Again sorry for the confusion. What I need is in a list of 9 sublists : lista2 = [['100',9].........[100;9] get another list of 9 sublist like this: [[100,7],[100,7]....[100_2,2],[100_2,2). This becouse 9-7 = 2 , so the residual should be the second value.
  • Thank you again for helping me with this. I will try your code!. It seems that it is working.
  • You area great bro! , Thank you for your time and help. I will be cheking this!
  • Khushhall! Thank for your time and help!. I will try this code!
  • Thanks!! , this is incredible. I will try this in Jupiter notebook.
  • I'm glad if it suits you - and i had fun improving it! :-) However - I hardly can see sth really useful in it... Don't get me wrong, but: are you sure that you have a task for which this is the best solution?
  • Lol - misunderstood! I didn't want to reject your acception, I was happy about it! :-) I just wanted to know, what's the usecase for this Algorithm, because I have no idea!
  • So basically I am using this code for something call CASPER methodology. I am a GIS analyst and I need this code to accomplish bigger set os instructions in the extrapolation process of CASPER. Right now I will choose the options of @James for my python desktops tool, but your solutions fit perfect for the Online version of my tool that uses jupiter notebooks.