Can I assign position of item in list? - list

ex = ['$5','Amazon','spoon']
I want to re-order this list, website - item - price.
Can I assign the index, for instance, ex.index('Amazon') = 1?
I'd like the result to be ['Amazon','spoon','$5']
I found information on how to swap positions, but I would like to know if I can assign an index for each item myself.

You cannot assign an index to an item, but you can build a permuted list according to a permutation pattern:
ex = ['$5','Amazon','spoon']
order = [1, 2, 0]
ex_new = [ex[i] for i in order]
print(ex_new)
#['Amazon', 'spoon', '$5']
Alternatively, you can overwrite the original list in place:
ex[:] = [ex[i] for i in order]
print(ex)
#['Amazon', 'spoon', '$5']

Related

How can I get the second to last item in a Kotlin List?

Let's say I have a List in Kotlin like:
val lst = MutableList<Int>()
If I want the last item, I can do lst.last(), but what about the second to last?
You can use the size of the list to compute the index of the item you want.
For example, the last item in the list is lst[lst.size - 1].
The second to last item in the list is lst[lst.size - 2].
The third to last item in the list is lst[lst.size - 3].
And so on.
Be sure the list is large enough to have an n'th to last item, otherwise you will get an index error
Use Collections Slice
val list = mutableListOf("one" , "two" , "three")
print(list.slice(1..list.size - 1))
This will give you the following result
[two, three]
Suppose you have 5 items in your val lst = MutableList<Int>() and you want to access the second last, it means listObject[3](list start with 0th index).
lst.add(101) - 0th Index
lst.add(102) - 1th Index
lst.add(103) - 2th Index
lst.add(104) - 3th Index
lst.add(105) - 4th Index
So you can try this
last[lst.size - 2] = 104 3rd Index
lst.size return 5, so if you use size - 1 it means you try to access last index 4th one, but when you use size - 2 it means you try to access the second last index 3rd.
Take secondLast element with null check,
fun <T> List<T>.secondLast(): T {
if (size < 2)
throw NoSuchElementException("List has less than two elements")
return this[size - 2]}
or use this, It simply return null if the index size does not match
myList.getOrNull(myList.lastIndex - 1)
drop first
lst.drop(1)
take from last
lst.takeLast(lst.size - 1 )
slice from..to
lst.slice(1..(lst.size-1) )
You may refer to this link https://kotlinlang.org/docs/collection-parts.html

How to get value from list using index?

I have to try to get one by one value from list using index and i have try to get index value and update my stage one by one and respectively.
my python code below :
for ress in status_list:
print"res", ress
#self.workflow_stages = ress
if ress:
self.workflow_stages = ress
for index, item in enumerate(status_list):
print "test::", index
index_init = index
print"index_init:::", index_init
next = index_init + 1
print "next", next
lent = len(status_list)
print"lent", lent
return True
Thanks.
This for index, item in enumerate(status_list): means that index variable holds your respective index of the status_list and item variable holds your value. So in given for loop, item will hold the value of the corresponding index.
Generally, if you don't use the enumerate functionality to iterate over a list, you can access a value of the list like this status_list[index]

How to get element in specific index from NSMutable dictionary (Swift 3)

I need to get the first element from NSMutable dictionary. I tried to get the element using for loop. but I am not getting the correct element because the Dictionary does not follow order. Is there any way I can get the element?
Here is my code:
for (count, i) in myMutableDict.enumerated() {
if count == 2 {
print(i.key)
}
}
As you know dictionary is un ordered collection Type.
let dictionary:Dictionary = ["YYZ": "Toronto Pearson", "DUB": "Dublin"];
for(index,obj) in dictionary.enumerated() {
print("index- \(index) - Object- \(obj)");
print("key- \(obj.key) - value- \(obj.value)");
}
Enumeration will provide you index and Objects of dictionary as above code says. If you want to work with index then you need to get all keys and keep it sorted so that you can get your key by providing index. And from that key you can get value from dictionary object. Piece of code is given below.
var keyList = Array(dictionary.keys);
keyList = keyList.sorted();
print("keyList \(keyList)");
let keyAtIndex = keyList[1];
print("value = \(dictionary[keyAtIndex]!)");

Enumerate list values into a list of dictionaries

I have a list of dictionaries, and I'm trying to assign dictionary key:value pairs based on the values of other other variables in lists. I'd like to assign the "ith" value of each variable list to ith dictionary in block_params_list with the variable name (as a string) as the key. The problem is that while the code appropriately assigns the values (as demonstrated by "pprint(item)"), when the entire enumerate loop is finished, each item in "block_params_list" is equal to the value of the last item.
I'm at a loss to explain this behavior. Can someone help? Thanks!
'''empty list of dictionaries'''
block_params_list = [{}] * 5
'''variable lists to go into the dictionaries'''
ran_iti = [False]*2 + [True]*3
iti_len = [1,2,4,8,16]
trial_cnt = [5,10,15,20,25]
'''the loops'''
param_list= ['iti_len','trial_cnt','ran_iti']#key values, also variable names
for i,item in enumerate(block_params_list):
for param in param_list:
item[param] = eval(param)[i]
pprint(item) #check what each item value is after assignment
pprint(block_params_list) #prints a list of dictionaries that are
#only equal to the very last item assigned
You've hit a common 'gotcha' in Python, on your first line of code:
# Create a list of five empty dictionaries
>>> block_params_list = [{}] * 5
The instruction [{}] * 5 is equivalent to doing this:
>>> d = {}
>>> [d, d, d, d, d]
The list contains five references to the same dictionary. You say "each item in 'block_params_list' is equal to the value of the last item" - that's an illusion, there's effectively only one item in "block_params_list" and you are assigning to it, then looking at it, five times over through five different references to it.
You need to use a loop to create your list, to make sure you create five different dictionaries:
block_params_list = []
for i in range(5):
block_params_list.append({})
or
block_params_list = [{} for i in range(5)]
NB. You can safely do [1] * 5 for a list of numbers, or [True] * 5 for a list of True, or ['A'] * 5 for a list of character 'A'. The distinction is whether you end up changing the list, or whether you change a thing referenced by the list. Top level or second level.
e.g. making a list of numbers, assinging to it does this:
before:
nums = [1] * 3
list_start
entry 0 --> 1
entry 1 --> 1
entry 2 --> 1
list_end
nums[0] = 8
after:
list_start
entry 0 -xx 1
\-> 8
entry 1 --> 1
entry 2 --> 1
list_end
Whereas making a list of dictionaries the way you are doing, and assigning to it, does this:
before:
blocks = [{}] * 3
list_start
entry 0 --> {}
entry 1 --/
entry 2 -/
list_end
first_block = blocks[0]
first_block['test'] = 8
after:
list_start
entry 0 --> {'test':8}
entry 1 --/
entry 2 -/
list_end
In the first example, one of the references in the list has to change. You can't pull a number out of a list and change the number, you can only put a different number in the list.
In the second example, the list itself doesn't change at all, you're assigning to a dictionary referenced by the list. So while it feels like you are updating every element in the list, you really aren't, because the list doesn't "have dictionaries in it", it has references to dictionaries in it.

removing cyclic substrings from python list

I have a Python list like the following:
['IKW', 'IQW', 'IWK', 'IWQ', 'KIW', 'KLW', 'KWI', 'KWL', 'LKW', 'LQW', 'LWK', 'LWQ', 'QIW', 'QLW', 'QWI', 'QWL', 'WIK', 'WIQ', 'WKI', 'WKL', 'WLK', 'WLQ', 'WQI', 'WQL']
If we pick, say the second element IQW, we see that the list has duplicates of this item HOWEVER its not noticeable right away. This is because it is cyclic. I mean the following are equivalent.
IQW, QWI, WIQ
Also it could be backwards which is also a duplicate so I want it removed. So now the list of duplicates are (the reverse of each of one these)
IQW, QWI, WIQ , WQI, IWQ, QIW
So essentially I would like IQW to be the only one left.
Bonus points, if the one that is remaining in the list is sorted alphabetically.
The way I did was to sort the entire list by alphabetical order:
`IQW`, `QWI`, `WIQ` , `WQI`, `IWQ`, `QIW` ->
`IQW`, `IQW`, `IQW`, `IQW`, `IQW` `IQW`
and then remove the duplicates.
However this also removes combinations say i have ABCD and CDAB. These are not the same because the ends only meet once. But my method will sort them to ABCD and ABCD and remove one.
My code:
print cur_list
sortedlist = list()
for i in range(len(cur_list)):
sortedlist.append(''.join(map(str, sorted(cur_list[i]))))
sortedlist = set(sortedlist)
L = ['IKW', 'IQW', 'IWK', 'IWQ', 'KIW', 'KLW', 'KWI', 'KWL', 'LKW', 'LQW', 'LWK', 'LWQ', 'QIW', 'QLW', 'QWI', 'QWL', 'WIK', 'WIQ', 'WKI', 'WKL', 'WLK', 'WLQ', 'WQI', 'WQL']
seen = set()
res = []
for item in L:
c = item.index(min(item))
item = item[c:] + item[:c]
if item not in seen:
seen.add(item)
seen.add(item[0]+item[-1:0:-1])
res.append(item)
print res
output:
['IKW', 'IQW', 'KLW', 'LQW']
Here is the solution I coded: If anyone has a better algo, I will accept that as answer:
mylist = list()
for item in copy_of_cur:
linear_peptide = item+item
mylist = filter(lambda x: len(x) == 3 , subpeptides_linear(linear_peptide))
for subitem in mylist:
if subitem != item:
if subitem in cur_list:
cur_list.remove(subitem)