简体   繁体   中英

Filtering a 2D array/list and replacing a value in python

I want to replace a number in this 2d array if the username already exists.

[["bob man", "0"], ["bill kill", "5"], ["nick", "5"]]

For example, when I receive the username "bob man", with the new number 44. I want to search my array and check if this username exists, and replace the number. If it doesn't exist, I want to append it to the array.

[["bob man", "44"], ["bill kill", "5"], ["nick", "5"]]

Is there a better way of storing this? I am new to python, and simple stuff like this seems much more complex than in js etc. Objects?

You can use numpy structured array if you would like to keep the order:

a = np.array([("bob man", 0), ("bill kill", 5), ("nick", 5)], dtype=[('name', 'U10'), ('value', 'i4')])
new_entry = np.array([('bob man', 44)], dtype=[('name', 'U10'), ('value', 'i4')])

if new_entry['name'] in a['name']:
  a['value'][a['name']==new_entry['name']] = new_entry['value']
else:
  a = np.append(a, new_entry)

I expect it to be faster than dictionaries, specially if you want to add more than one entry, you can include them all in new_entry and change code a bit to check array-wise to be faster.

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