简体   繁体   中英

Create a new list enumerating the random integers from another list in Python

I need to simulate a certain scenario.

So I'm defining a variable which generates a loop of a random number of integers.

I get for example:

list = [2, 35, 4, 8, 56, 10]

Then, I'm generating this random list 50 times through another loop and I store the data into a dictionary to visualize a Pandas Dataframe.

data_dict = {'random_numers': list}
data_dict_pd = pd.DataFrame(data_dict)

So I get for example this:

[1, 16, 6, 6, 1, 10]
[3, 8, 4, 4, 1, 20, 7, 25, 12]
[14, 8, 16, 4, 11, 18, 5, 15, 24, 2, 15, 5]
[7, 24, 1, 14]
[5, 14, 19, 24, 1]
... 50 times. 

Now, I need to create another column enumerating each number in each list of elements, to get the following, based on the previous results:

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
...50 times. 

Actually, came up with the following but it's wrong:

new_list = []
 for index in enumerate(list)
    new_list.append(index)

Any better idea?

I would strongly suggest changing the name of your list, as list is used for Python lists.

Assuming you change it to l , I would use:

l = [2, 35, 4, 8, 56, 10]
new_list = []
for i in range(1, len(l) + 1):
    new_list.append(i)
print(new_list)

Output: [1, 2, 3, 4, 5, 6]

If what you need is to iterate a list of lists, and incorporating @deceze suggestions (provided that you don't rename list ):

lists = [
    [1, 16, 6, 6, 1, 10],
    [3, 8, 4, 4, 1, 20, 7, 25, 12],
    [14, 8, 16, 4, 11, 18, 5, 15, 24, 2, 15, 5],
    [7, 24, 1, 14],
    [5, 14, 19, 24, 1]
]

new_lists = [list(range(1, len(lst) + 1)) for lst in lists]
print(new_lists)

Output: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

new_list = []
for index in range(1,len(list)+1)
    new_list.append(index)

should be used in place of enumerator,as it will going to return the pair.

Thank you,

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