How to print index and value in array in python - python

I am trying to print text with an index and its value. This is the code
test_list = [1, 4, 5, 6, 7]
for index, value in enumerate(test_list):
print("S1_vec('index')<=", value)
Getting output
S1_vec('index')<= 1
S1_vec('index')<= 4
S1_vec('index')<= 5
S1_vec('index')<= 6
S1_vec('index')<= 7
But I want my output to print an index value
S1_vec('0')<= 1
S1_vec('1')<= 4
S1_vec('2')<= 5
S1_vec('3')<= 6
S1_vec('4')<= 7
Can anyone please help me to correct this issue? Thanks

Currently, you are passing index as literal string which is incorrect.
Use f-strings for python3.6+:
test_list = [1, 4, 5, 6, 7]
for index, value in enumerate(test_list):
print(f"S1_vec('{index}')<= {value}")
or format() for lower versions:
test_list = [1, 4, 5, 6, 7]
for index, value in enumerate(test_list):
print("S1_vec('{}')<= {}".format(index, value))

If you're using a sufficiently recent Python, f-strings are probably easiest:
print(f"S1_vec('{index}') <= {value}")

Related

How can I find the missing index using python pandas?

Example
Order_ID Name
1 Man
2 Boss
5 Don
7 Lil
9 Dom
10 Bob
Want to get an output as:
3 4 6 8 are the missing Order_ID
Try using a list comprehension with range:
print([i for i in range(1, 10) if i not in df['Order_ID']])
Output:
[3, 4, 6, 8]
Solution for generate missing values from index dynamically by maximum and minimum values:
print (np.setdiff1d(np.arange(df.index.min(), df.index.max() + 1), df.index).tolist())
[3, 4, 6, 8]
Convert the list to set and compute its difference with a set that contains integers ranging from min(lst) and max(lst).
lst=df["Order_ID"].to_list()
sorted(set(range(lst[0], lst[-1])) - set(lst))
> [3, 4, 6, 8]
Try this code;
Code Syntax
missData = list(filter(lambda x: x not in df['Order_ID'], range(1, df['Order_ID].max()+1)))
print(f"{missData} are the missing Order_ID")
Output
[3, 4, 6, 8] are the missing Order_ID
[Program finished]

How do I sort with multiple conditions on python?

6 7 5 2 12
0 2 3 6 12
2 8 5 4 13
4 3 5 7 14
def getMinIndex(list, start, stop):
n=len(list)
min_index = start
for i in range(start,stop):
if list[i][4] > myList[min_index][4]:
min_index = i
return min_index
def swapElements(list,i,j):
temp = list[i]
list[i] = list[j]
list[j] = temp
With this code I manage to sort the last element on the list which is index 4 but I'm having problem to sort the 1st index as I want the results to be like this.
0 2 3 6 12
6 7 5 2 12
2 8 5 4 13
4 3 5 7 14
So if the last element is the same after sorting then I want to sort the 1st element. Can anyone help? Thanks :D
What you're looking for is a key function for items on your list. Let me illustrate with an example.
Sorting keys
Suppose you have a list of people. You want to sort them by height. You can't just sort them using sorted because they aren't comparable by default the way numbers are. You need to specify the key used for sorting. The key is the characteristic you want to sort on. In this case it could look like:
sorted(people, key=lambda person: person.height)
or, if you find the lambda notation confusing:
def get_height(person):
return person.height
sorted(people, key=get_height)
Sorting tuples
A tuple is a finite sequence of items: (2,3) (2-tuple or pair), (-3, 2, 1) (3-tuple) and so on. Tuples are sorted alphabetically automatically. You don't need to do anything.
What's special in your case is that you don't want to sort by the first element, then by the second, and so on. You want to sort by the fourth and then by the first.
This is where keys enter the scene.
Tying it all together
You need a key function that will turn (a, b, c, d, e) into (e, a) which means: sort by the fifth column first and then by the first one:
def sorting_key(item):
return (item[4], item[0])
Then you can just call:
sorted(items, key=sorting_key)
# or with a lambda
sorted(items, key=lambda item: (item[4], item[0]))
Getting the index corresponding to a minimum
I noticed that your function returns a minimum corresponding to the element. You can sort the whole thing and take the first element. Alternatively, you can use the built-in min function and provide it the sorting key.
The only thing you need to take into account is that min returns the corresponding value, not the index. You can work around this with:
min_index, min_value = min(enumerate(items), key=lambda (index, value): (value[4], value[0]))
enumerate pairs list items with their indexes so [a, b, c] becomes [(0, a), (1, b), (2, c)]. Then you sort these pairs as if the indexes weren't present: key accepts index as the first argument in a tuple but ignores it completely.
You can use operator.itemgetter and use it for a custom sorting key function which you can pass to one of the built-in sort functions:
> from operator import itemgetter
> lst = [
[2, 8, 5, 4, 13],
[6, 7, 5, 2, 12],
[4, 3, 5, 7, 14],
[0, 2, 3, 6, 12]
]
# use tuple of last and first elmnt as sorting key
> sorted(lst, key=itemgetter(-1, 0))
[
[0, 2, 3, 6, 12],
[6, 7, 5, 2, 12],
[2, 8, 5, 4, 13],
[4, 3, 5, 7, 14]
]

Python: for-loop wrong output [duplicate]

This question already has answers here:
Removing elements from a List in Python
(3 answers)
Closed 6 years ago.
Can't understand why it missing some indexes in loop?
Index number 3 for example.
I just want to delete the unique elements this way. I know another one but I don't know what's wrong with this one (or me).
lst = [2, 7, 1, 9, 3, 5, 2, 1]
def check(lst):
result = lst
print(lst) #checking
for num in lst:
print("index:", num) #checking
print("num:", num) #checking
if lst.count(num) < 2:
print("count:", lst.count(num)) #checking
result.remove(num)
return(result)
print(check(lst))
Output
[2, 7, 1, 9, 3, 5, 2, 1]
index: 2
num: 2
index: 7
num: 7
count: 1
index: 9
num: 9
count: 1
index: 5
num: 5
count: 1
index: 1
num: 1
[2, 1, 3, 2, 1]
You're removing items from a list as you're iterating over it, which you shouldn't do.
(result = lst does NOT make a copy of lst; it creates a new name which refers to the same object.)
If you just want to remove duplicate elements, you can use a set (although you may lose your ordering):
lst = list(set(lst))

I need to know why this is the output for these python condition

numbers=[i**3 for i in range (10) if i**3%3==1]
print(numbers)
#gets 1,64,343
Why is 1, 64, 343 the answer?
This is equivalent to the code:
for i in range(10):
if (i*i*i) % 3 == 1:
numbers.append(i*i*i)
print (numbers)
You are checking if the remainder obtained when the cube of a number from 1 to 10 is divided by 3 is equal to 1. If it is, you are adding it to a list and printing it.
The meaning of **
ex: 2**3= 2*2*2 #this means 2 to the power 3 = 8
The meaning of %
ex: 5%2= 1 #the sign means module, that means the remaining value after divide 5 by 2, it is one.
in your way, the correct path to write the for each is
for i in range(0,10):
value = i**3
if(value%3 == 1):
print("the value is {0}".format(value))
so the result is :
the value is 1
the value is 64
the value is 343
bit explanation inside the for loop
first get the i = 0, at this point value = 0*0*0 = 0, then value%3=0
then get the i=1, at this point value = 1*1*1 = 1 ,the 'value%3' means 1%3 = 1, so the answer i 1
.... like this see about other conditions also. hope this will help to you.
first i is in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
then if (i*i*i) rem 3 is equal to 1
it selects (i*i*i)
and for [1,4,7]: (1*1*1)%3==1, (4*4*4)%3==1 and (7*7*7)%3==1:
1*1*1=1 and 1/3=0 :remainder=1
4*4*4=64 and 64/3=21 :remainder=1
7*7*7=343 and 343/3=114 :remainder=1
so the output is:
[1*1*1, 4*4*4, 7*7*7] which is [1, 64, 343]
your code:
numbers=[i**3 for i in range (10) if i**3%3==1]
print(numbers)
and this code:
numbers=[]
for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
if (i*i*i) % 3 == 1:
numbers.append(i*i*i)
print(numbers)
output this:
[1, 64, 343]

Printing a histogram

I have a list of integer percentages which I need to print using the following pattern:
The index of a value, a tab (8 spaces), a '*' printed for each percentage point
also if the value for an index is 0, print 'less than 1 percent'
I have tried this code:
for b in new_tally:
if b > 0:
print new_tally[b], \t, '*' * b
else:
print 'Less than 1% of words had this length'
However I keep getting the error code: list index out of range.
I do not understand this at all, can someone point out what I have done wrong?
I think the code you wanted was:
>>> new_tally = [5, 7, 8, 6, 4, 2]
>>> for i, b in enumerate(new_tally, 1):
print i, ':', b, '*' * b
1 : 5 *****
2 : 7 *******
3 : 8 ********
4 : 6 ******
5 : 4 ****
6 : 2 **
The cause of the original traceback is that list members are looked up using square brackets instead of parentheses. new_tally(i) is a function call. new_tally[i] is an indexed lookup.
for key,val in new_tally.iteritems():
print('{k} {a}'.format(k=key,a='*'*int(val)))
or, if you want the histogram sorted in descending order of frequency:
import operator
for key,val in sorted(new_tally.items(),key=operator.itemgetter(1),reverse=True):
print('{k} {a}'.format(k=key,a='*'*int(val)))
first piece:
new_tally = [5, 7, 8, 6, 4, 2]
for b in new_tally:
print b
second piece:
new_tally = [5, 7, 8, 6, 4, 2]
for i in range(len(new_tally)):
print i, new_tally[i]
the above two do approximately the same thing. you are mixing up between visiting elements in sequence (first approach) versus accessing list elements by sequential index (second approach).

Categories