2

I am working with Python 2.7.12

I have the following list:

t = [1,2,3,4,5] 

I want to have following output:

1+1, 1+2, 1+3, 1+4, 1+5, 2+2, 2+3, 2+4, 2+5, 3+3, 3+4, 3+5, 4+4, 4+5

I tried:

zip(t,t[1:])

but the output was:

[(1, 2), (2, 3), (3, 4), (4, 5)]  

Then, I also tried:

 zip(t,t)    

but the output was:

[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)] 
Mohd
  • 5,523
  • 7
  • 19
  • 30
satyamaale
  • 21
  • 3
  • t is not a list here but a tuple. Assuming thats a type do we really know that input list is always sorted? – amrx May 31 '17 at 17:25
  • Dear Frankyjuang, My question is related to iteration of one element of list with rest of the elements. The question you have mentioned is between TWO lists. – satyamaale May 31 '17 at 17:34
  • Then just set `list2 = list1`. – Ken Y-N Jun 01 '17 at 08:03

6 Answers6

1

May be list1=[1,2,3,4,5]

for i in list1:
    for j in list1[i-1:]:
        print str(i)+"+"+str(j)
Vijayabhaskar J
  • 417
  • 2
  • 4
  • 17
1

You can use two for loops to iterate through the list as the following:

t = ('1', '2', '3', '4', '5')
result = []
for i in xrange(len(t)-1):
    for j in xrange(i, len(t)):
        result.append(t[i] + '+' + t[j])
print ', '.join(result)

output:

1+1, 1+2, 1+3, 1+4, 1+5, 2+2, 2+3, 2+4, 2+5, 3+3, 3+4, 3+5, 4+4, 4+5
Mohd
  • 5,523
  • 7
  • 19
  • 30
0

You can try this:

from itertools import combinations_with_replacement
t = ('1','2','3','4','5')
sums = [i[0]+"+"+i[1] for i in list(combinations_with_replacement(t, 2))]

Output:

['1+1', '1+2', '1+3', '1+4', '1+5', '2+2', '2+3', '2+4', '2+5', '3+3', '3+4', '3+5', '4+4', '4+5', '5+5']
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • Dear Damian, Thanks. I tried it and output is ['1+2', '1+3', '1+4', '1+5', '2+3', '2+4', '2+5', '3+4', '3+5', '4+5']. Still missing 1+1, 2+2, 3+3, 4+4, 5+5. Any idea? – satyamaale May 31 '17 at 17:20
  • I believe you may be referring to another user, but I have changed my code above to get the answer you are looking for. – Ajax1234 May 31 '17 at 17:24
  • Dear Ajax1234, The solution is perfect. Thanks. – satyamaale May 31 '17 at 17:37
  • Glad I could help. Please mark this answer as accepted so other users know it has been answered. Thank you. – Ajax1234 May 31 '17 at 17:40
0
import itertools

t = ('1','2','3','4','5')

for t1, t2 in itertools.product(t, t):
    if t1 <= t2:
        print('%s + %s' % (t1, t2))
ngoldbaum
  • 5,430
  • 3
  • 28
  • 35
0

Assuming t is a list and not always sorted.

t.sort()
t_len = len(t)
output = []
for i in xrange(t_len - 1):
   j = 1 if i == 0 else i
   for k in xrange(j, t_len):
      output.append(str(t[i]) + "+" + str(t[j]))
print output
amrx
  • 673
  • 1
  • 9
  • 23
0

In three lines:

list = range(1,6)
lists = [list[(i-1):] for i in list]
output = [str(i[0]) + '+' +str(j) for i in lists for j in i]
artona
  • 1,086
  • 8
  • 13