Printing list items along with index - python

Suppose I have a list a = [x, y, z], and I want to print
1. x
2. y
3. z
I can do it, but it is a bit lengthy, like
c = 1
for i in a:
print(str(c) + "." + i)
c += 1
Is there a shorter way of doing it? Any help is appreciated. Thanks in advance.

What about this example, where i is the index and e would be each item from a list.
for i,e in enumerate(a):
print (str(i + 1) + '.', e)
As #niemmi suggests, you could also start the index at 1:
for i,e in enumerate(a, start=1):
print (str(i) + '.', e)

Related

Group string by 3 character to a List

for example, I have string "25037654", and I want to Group the string by 3.
but, since the string is 8 character, and 8 % 3 is not 0. it have remainder. and I want the final List is ["25", "037", "654"], the first Index will only accept the remainder, for example 1 or 2 character
I think this code may satisfy your requirement.
First get the idx of every slice, then cut this string to each substring.
str_num = "25037654"
idx = [len(str_num)%3+3*i for i in range(len(str_num)//3+1)]
print(idx) # [2, 5, 8]
if(idx[0]!=0):
idx = [0]+idx
res = [str_num[idx[i]:idx[i+1]] for i in range(len(idx)-1)]
print(res) # ['25', '037', '654']
One easy way, in this case, is to use f-string:
s = "25037654"
output = f"{int(s):,}".split(',')
print(output) # ['25', '037', '654']
The above won't work if the input is not numeric. Then try:
leading = len(s) % 3
output = ([s[:leading]] if leading else []) + [s[i:i+3] for i in range(leading, len(s), 3)]
Thanks everyone who respond and answer My Question.
after a few moments I post my question. I found the answer LoL
it's the Long Way, my version. thanks Guyss
s = "25037654"
if len(s) % 3 == 2:
fn = s[0:2]
xx = s[2:len(s)]
group = list(map(''.join, zip(*[iter(xx)]*3)))
final = fn + " " + " ".join(group)
elif len(s) % 3 == 1:
fn = s[0:1]
xx = s[1:len(s)]
group = list(map(''.join, zip(*[iter(xx)]*3)))
final = fn + " " + " ".join(group)
elif len(s) % 3 == 0:
group = list(map(''.join, zip(*[iter(s)]*3)))
final = " ".join(group)
print(final) # 25 037 654
t = "25037654555"
i, j = divmod(len(t), 3) # i - int part, j - remainder
print([t[:j]] + [t[j+(i-1)*3:j+i*3] for i in range(1,i+1) ])
Result:
['25', '037', '654', '555']
You can try my version:
s = "25037654"
rem = len(s)%3
lst = []
i = 0
while i < len(s)-2:
if i == 0:
lst.append(s[:rem])
i+=rem
else:
lst.append(s[i:i+3])
i+=3

strings and prints them as columns from list in python

I have list of lists of strings like this:
[['today'], ['is'], ['rainy'], ['day']]
I want to print each word vertically in python. I want to output something like this
t i r d
o s a a
d i y
a n
y y
You could try itertools.zip_longest
from itertools import zip_longest
lst = [['today'], ['is'], ['rainy'], ['day']]
print('\n'.join([' '.join([y or ' ' for y in x]) for x in zip_longest(*[i[0] for i in lst])]))
Output:
t i r d
o s a a
d i y
a n
y y
You can do this will a loop.
l = [['today'], ['is'], ['rainy'], ['day']]
max_len = len(max(l, key=lambda x: len(x[0]))[0])
out = ''
for idx in range(max_len):
for item in l:
small_item = item[0]
if len(small_item) > idx:
out += small_item[idx]
out += "\t"
else:
out += " \t"
out += "\n"
print(out)
t i r d
o s a a
d i y
a n
y y
Idea behind this is simple. You have to find the length of longest string you have. Then basically you want to pick up each item from each string if that element is valid, else add a empty space. Add tabs and newlines to format as you want.
lst = [['today'], ['is'], ['rainy'], ['day']]
max_len = len(max(lst, key=lambda x: len(x[0]))[0])
for i in range(max_len):
for word in lst:
try:
print(word[0][i], end=' ')
except IndexError:
print(' ', end=' ')
print()
Output:
t i r d
o s a a
d i y
a n
y y

i have a problem with strings and for loop in python

I have a string and I saved it inside a variable.
I want to change even characters to capitalize with for loop.
so i give my even characters and capitalized it. But
i cant bring them with odd characters .
can someone help me?
here is my code:
name = "mohammadhosein"
>>> for even in range(0, len(name), 2):
... if(even % 2 == 0):
... print(name[even].title(), end=' ')
...
M H M A H S I >>>
>>> ###### I want print it like this:MoHaMmAdHoSeIn```
I assume you are quite new to programing, so use a the following for loop:
name = "mohammadhosein"
output = ''
for i, c in enumerate(name):
if i % 2 == 0:
output += c.upper()
else:
output += c
# output will be 'MoHaMmAdHoSeIn'
enumerate will give you a pair of (i, c) where i is an index, starting at 0, and c is a character of name.
If you feel more comfortable with code you can use a list comprehension and join the results as follows:
>>> ''.join([c.upper() if i % 2 == 0 else c for i, c in enumerate(name)])
'MoHaMmAdHoSeIn'
As #SimonN has suggested, you just needed to make some small changes to your code:
for index in range(0, len(name)):
if(index % 2 == 0):
print(name[index].upper(), end='') # use upper instead of title it is more readable
else:
print(name[index], end='')
print()

How to perform group by in python

I am trying to find the average of certain numbers in python
For example:
A={('A','B',1):1,('A','B',2):4,('A1','B1',2):5,('A1','B1',1):6}
A is dictionary and my output should be
B={('A','B'):1+4/2,('A1','B1'):11/2)}
I got the logic by using some FOR loops and IF condition but it is too time consuming.
Can anyone tell me a faster way of getting the output.
my logic
for i in A:
# lis.append(i)
lis.append((i, A[i]))
for j in lis:
if (j[0][0], j[0][1]) not in pro_loc_comb:
pro_loc_comb.append((j[0][0], j[0][1]))
B= {}
print pro_loc_comb
for x in pro_loc_comb:
a = 0
count = 0
for j in lis:
if (x[0] == j[0][0]):
if (x[1] == j[0][1]):
count = count + 1
a = (a + j[1])
B[(x[0], x[1])] = a / float(count)
print B
Thanks in advance
Since you didn't include your solution, I used this:
from __future__ import division
A={('A','B',1):1,('A','B',2):4,('A1','B1',2):5,('A1','B1',1):6}
B={}
C={}
for x in A:
val= A[x]
y,z,n=x
if (y,z) in B:
B[(y,z)]+=val
C[(y,z)]+=1
else:
B[(y,z)]=val
C[(y,z)]=1
for x in B:
B[x]=B[x]/C[x]

How can I subtract 2 string or list in python?

I have very large strings in my codes. I would like to detect different characters between the strings. Here is an example what I mean:
a='ababaab'
b='abaaaaa'
a=a-b
print(a)
I expect kind of like these; 'bb' or '000b00b'
I know sounds weird but I really need this.
You could do:
a = 'ababaab'
b = 'abaaaaa'
a = ''.join(x if x != y else '0' for x, y in zip(a, b))
# '000b00b'
# OR
a = ''.join(x for x, y in zip(a, b) if x != y)
# 'bb'
Here is the example: It works wih list
listA = ["a","b"]
listB = ["b", "c"]
listC = [item for item in listB if item not in listA]
print listC
Output
# ['c']
You can create custom function as following:
(assumption length of both strings are equal)
def str_substract(str1, str2):
res = ""
for _ in xrange(len(str1)):
if str1[_] != str2[_]:
res += str1[_]
else:
res += "0"
return res
a='ababaab'
b='abaaaaa'
print str_substract(a, b)
output:
000b00b
result = ''
for temp in a:
result += temp if temp not in b else '0'
Use zip:
res = ''
for i, j in zip(a, b):
if i == j:
res += '0'
else:
res += i
Using a list to store the result is probably more efficient.
if you want s1 - s2 :
s1 = 'ababaab'
s2 = 'abaaaaa'
for i,j in zip(s1,s2):
if (i != j):
print i,
output : bb

Categories

Resources