Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there some method of array like set in python?

As I know in python i can set a list to a unique list like:

In [12]: a=range(12)

In [13]: a.append(5)

In [14]: a.append(4)

In [15]: a.append(5)

In [16]: a
Out[16]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 5, 4, 5]

In [17]: set(a)
Out[17]: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])

it is very useful for some scene, i just want to know how to this in javascript,

like image 348
timger Avatar asked Dec 21 '11 05:12

timger


People also ask

Can you have a set of arrays in Python?

First of all, lists are part of the core Python programming language; arrays are a part of the numerical computing package NumPy. Therefore, you have access to NumPy arrays only if you load the NumPy package using the import command.

Can a Python set have different types?

Set elements are unique. Duplicate elements are not allowed. A set itself may be modified, but the elements contained in the set must be of an immutable type.

What is Python array like?

The term "array-like" is used in NumPy, referring to anything that can be passed as first parameter to numpy. array() to create an array (). As per the Numpy document: In general, numerical data arranged in an array-like structure in Python can be converted to arrays through the use of the array() function.

Does Javascript have sets like Python?

Javascript does not have the notion of sets. However, you can use a side effect of the fact that objects cannot have duplicate property names to replicate the functionality of a set, as seen on this blog article about the topic.


2 Answers

Javascript does not have the notion of sets. However, you can use a side effect of the fact that objects cannot have duplicate property names to replicate the functionality of a set, as seen on this blog article about the topic.

From the article:

var your_array = ['a', 'a', 'a', 'b', 'b'],
    set = {};
for (var i = 0; i < your_array.length; i++)
   set[your_array[i]] = true;
list = [];
for (var item in set)
   list.push(item);

EDIT in 2017: This is no longer true, JS got set support! MDN Docs

empty_set = new Set()
three_element_set = new Set([1, 1, 1, 2, 2, 3])
three_element_set.add(3) // still three element set
like image 156
Interrobang Avatar answered Oct 27 '22 15:10

Interrobang


No, there isn't. JS is pretty basic, you have to either do it yourself or find a library where someone else has already done it.

The standard way to do this is usually insert elements into a hash, then collect the keys - since keys are guaranteed to be unique. Or, similarly, but preserving order:

function uniq(arr) {
  var seen = {}, result = [];
  var len = arr.len;
  for (var i = 0; i < len; i++) {
    var el = arr[i];
    if (!seen[el]) {
      seen[el] = true;
      result.push(el);
    }
  }
  return result;
}
like image 42
Amadan Avatar answered Oct 27 '22 14:10

Amadan