-2

I want to concatenate integer and string value, where integer is in a 2D list and string is in a 1D list.

['VDM', 'MDM', 'OM']

The above mentions list is my string list.

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

The above mentioned list is my integer list.

I have tried this code:

for i in range(numAttr):
    for j in range(5):
        abc=[[attr[i]+counts[i][j]]]
print(abc)

Here numAttr is the number of element in the first 1D list. and second 2D list is a static list i.e. for any dataset the 2D list will not change.

The above code showing the error:

TypeError: can only concatenate str (not "int") to str

I want a list output which looks like this:

[['VDM:1','VDM:2','VDM:3','VDM:4','VDM:5'],['MDM:1','MDM:2','MDM:3','MDM:4','MDM:5'],['OM:1','OM:2','OM:3','OM:4','OM:5']]
  • As asked, this question is too broad; it does not have a proper [mre]. The question in the title seems to ask only about doing the concatenation for a single string-integer pair, which is properly scoped; but the post asks for a way to get this result repeated across an entire nested list - how to repeat the process for each element of the nested list is a *separate question*. As such, this is not a good signpost for the canonical duplicate (it would be not be a good question even if the duplicate did not exist). Voting for deletion. – Karl Knechtel Jul 27 '22 at 02:32

2 Answers2

1

Use the nested list comprehension below:

>>> l = ['VDM', 'MDM', 'OM']
>>> l2 = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
>>> [[a + ':' + str(b) for b in c] for a,c in zip(l, l2)]
[['VDM:1', 'VDM:2', 'VDM:3', 'VDM:4', 'VDM:5'], ['MDM:1', 'MDM:2', 'MDM:3', 'MDM:4', 'MDM:5'], ['OM:1', 'OM:2', 'OM:3', 'OM:4', 'OM:5']]
>>> 

Or:

>>> l = ['VDM', 'MDM', 'OM']
>>> l2 = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
>>> [['{}:{}'.format(a, b) for b in c] for a,c in zip(l, l2)]
[['VDM:1', 'VDM:2', 'VDM:3', 'VDM:4', 'VDM:5'], ['MDM:1', 'MDM:2', 'MDM:3', 'MDM:4', 'MDM:5'], ['OM:1', 'OM:2', 'OM:3', 'OM:4', 'OM:5']]
>>> 

Or:

>>> l = ['VDM', 'MDM', 'OM']
>>> l2 = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
>>> [['%s:%s' % (a, b) for b in c] for a,c in zip(l, l2)]
[['VDM:1', 'VDM:2', 'VDM:3', 'VDM:4', 'VDM:5'], ['MDM:1', 'MDM:2', 'MDM:3', 'MDM:4', 'MDM:5'], ['OM:1', 'OM:2', 'OM:3', 'OM:4', 'OM:5']]
>>> 

Or f-strings (version >= 3.6):

>>> l = ['VDM', 'MDM', 'OM']
>>> l2 = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
>>> [[f'{a}:{b}' for b in c] for a,c in zip(l, l2)]
[['VDM:1', 'VDM:2', 'VDM:3', 'VDM:4', 'VDM:5'], ['MDM:1', 'MDM:2', 'MDM:3', 'MDM:4', 'MDM:5'], ['OM:1', 'OM:2', 'OM:3', 'OM:4', 'OM:5']]
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
-1

Change the line abc=[[attr[i]+counts[i][j]]] to abc=[[attr[i]+':'+str(counts[i][j])]]

Carlos Gonzalez
  • 858
  • 13
  • 23