Json with multiple values under single key to json array python - arrays

I want to convert Json which is in this form
{'number':[1,2,3,3],'addr':['a',b","c","d"]}
I want json in this form
[{'number':1,'addr':'a'},{'number':2,'addr':'b'},{'number':3,'addr':'c'},{'number':3,'addr':'d'}]
I have tried to search this in all platform but couldn't find anything

All you need to do is create a new list, iterrate the length of the sublist and and add a new dictionary for each key,value pair and add it to the empty list.
current = {'number':[1,2,3,3],'addr':['a',"b","c","d"]}
lst = []
num_elem = len(current['number'])
for i in range(num_elem):
item = {k:current[k][i] for k in current.keys()}
lst.append(item)
or if you want an unreadable oneliner:
[{i:current[i][k],j:current[j][k]} for i,j in [current.keys()] for k in range(len(current[i]))]
OUTPUT:
[{'number': 1, 'addr': 'a'},
{'number': 2, 'addr': 'b'},
{'number': 3, 'addr': 'c'},
{'number': 3, 'addr': 'd'}]

Related

Add Array in single line to new file and load Array in single line

Hey I'm writing a simple game, where I want to save progress and load it at another point.
One one the elements to save is an array. I want to save this array in one single line as an array and also load it again as an array, but it only takes the first element and the following elements overwrite further content
Example (wrong) - Save Data
player_1 = "name"
array = [1, 2, 3]
count = 1000
File.open("game.txt", "w+") do |file|
file.puts player_1
file.puts array
file.puts count
end
Example (wrong) - Load Data
file_data = File.open("game.txt").readlines.map(&:chomp)
player_1 = file_data[0]
array = file_data[1]
count = file_data[2]
OUTPUT: TEXTFILE
name
1
2
3
1000
So I converted the array to a string and write it in text-file (it works but seems inconvenient)
to save the array
file.puts double_checker.to_s
# Output: String
"[1, 2, 3]"
to load the array (load string from text file, delete special chars, convert it back to array, convert elements to integers)
# Converts String back to Array, digits convert to Integers
double_checker = double_checker.delete(" []").split(",").map { |s| s.to_i }
# Output: Array
[1, 2, 3]
Now my question: Is there a way to store the array directly into to text file (in one line) and read it the same way, so I can store the array straight into a variable?
Or is it only possible to store Strings into a text file?
I'm trying to figure out how I can use write/read to save and load files for example a game progress.
One option would is to use Marshal::dump and Marshal::load.
player_1 = "name"
array = [1, 2, 3]
count = 1000
File.open("game.txt", 'wb') do |f|
f.write(Marshal.dump([player_1, array, count]))
end
#=> 28
player_1, array, count = Marshal.load(File.binread("game.txt"))
#=> ["name", [1, 2, 3], 1000]
Note that it is not guaranteed that an object serialized using dump with one version of Ruby will be readable with load with a later version of Ruby. On the other hand, Marshal can be used to serialize a wide range of Ruby objects.
"The marshaling library converts collections of Ruby objects into a byte stream", which is why Marshal's serialized objects should be written to and read from binary files.
Another option is to use JSON#generate and JSON#parse.
require 'json'
File.write("game.txt", JSON.generate([player_1, array, count]))
#=> 21
player_1, array, count = JSON.parse(File.read("game.txt"))
#=> ["name", [1, 2, 3], 1000]
One can alternatively use JSON::Ext::Generator::GeneratorMethods::Array#to_json to serialize the array:
player_1, array, count].to_json
#=> "[\"name\",[1,2,3],1000]"

Assigning int number to an array

I would like to assign int to an array. What I have is;
label = ['rest', 'rest', 'ball', 'cat', 'rest']
And I want to get is somethin like this, the int order is not important;
labeled = [1, 1, 2, 3, 1]
How I did was, I find the np.unique(label) and make dict:
labelDict = dict(zip(label, np.arange(1,4))
But, I'm stuck at the next step which is to assign this integer to that array label.
You can create a mapping dictionary, similar to what you are doing already:
mapping = {i:idx for idx, i in enumerate(set(label))}
Then, use the mapping to remap the labels:
output = [mapping[i] for i in label]
There's no need for numpy, the task can be easily accomplished with base Pyhton.

Find the index by current sort order of an array in ruby

If there is an array
array A = ["a","b","c","d"] #Index is [0,1,2,3]
And it's sorted to.
array A = ["d","c","b","a"]
I need an array that returns me the updated index based on the sorted order
[3,2,1,0]
I'm trying to find a solution to this ruby
UPDATE to the question
If a is sorted to
array A = ["d","b","c","a"] #not a pure reverse
Then the returned index array should be
[3,1,2,0]
You need to create a mapping table that preserves the original order, then use that order to un-map the re-ordered version:
orig = %w[ a b c d ]
orig_order = orig.each_with_index.to_h
revised = %w[ d c b a ]
revised.map { |e| orig_order[e] }
# => [3, 2, 1, 0]
So long as your elements are unique this will be able to track any shift in order.
Here is one way to do this:
original_array = ["a","b","c","d"]
jumbled_array = original_array.shuffle
jumbled_array.map {|i| original_array.index(i)}
#=> [1, 3, 0, 2]
Note:
In this sample, output will change for every run as we are using shuffle to demonstrate the solution.
The solution will work only as long as array has no duplicate values.
If you do wish to solution to work with arrays with duplicate values, then, one possibility is to look at object_id of array members while figuring out the index.
jumbled_array.map {|i| original_array.map(&:object_id).index(i.object_id)}
This solution will work as long as jumbled_array contains element from original_array and no elements were recreated using dup or something that results in change in object_id values
You can use the map and index methods.
arr = ["a","b","c","d"]
sort_arr = ["d","c","b","a"]
sort_arr.map{|s| arr.index(s)}
# => [3, 2, 1, 0]

How to loop over array of hashes and remove a hash where a key has a specific value?

I'm trying to loop over an array of hashes containing a set of keys and values, in this loop I want to check whether any key (or a set of specific keys, whatever that is most simple) has a certain value.
This is what I've got so far, but it doesn't work as the hashes containing a key with the value dollar is still present within the array:
remove_currency = [{a: 'fruit', b: 'dollar'}, {a: 'fruit', b: 'yen'}]
currency = 'dollar'
remove_currency.delete_if { |_, v| v == currency }
Hope I made myself clear enough!
things = [{foo: 3, bar: 42}, {baz: 5, quiz: 3.14}]
things.reject { |thing| thing.values.include? 42 }
# => [{:baz=>5, :quiz=>3.14}]

How to pick elements in fixed interval in an array (python)

Given array=[1, 2, 3, 4, 5, 6]
I want to choose the 0-th 2-nd, 4-th index value to build a new array
array1=[1, 3, 5]
Could someone show me how to do using python? Thanks~
If it is just 0, 2, and 4, you can use operator.itemgetter():
from operator import itemgetter
array1 = itemgetter(0, 2, 4)(array)
That will be a tuple. If it must be a list, convert it:
array1 = list(itemgetter(0, 2, 4)(array))
If the point is to get the even numbered indices, use slicing:
array1 = array[::2]
Whichever you are looking for, you could use a list comprehension:
array1 = [array[i] for i in (0, 2, 4)]
or
array1 = [array[i] for i in xrange(0, len(array), 2)]
You can try something like this. In python the nth term of a list has index (n-1). Suppose the first element you want is 2, which happens to be the element 1 of array. Just save the first element index in a variable. Append it to the new list array1 and increase the index by 2. Continue doing this until the list array is exhausted.
from numpy import*
array=[1,2,3,4,5,6]
array1=[]
term=1
while term<len(array): # if the array length is 6 then it will have upto element 5.
array1.append(array[term])
term=term+2 # 2 is the gap between elements. You can replace it with your required step size.

Resources