-2

Is there a way to use the elements of a string-list first as strings and then as int?

l = ['A','B','C']

for n in l:
    use n as string (do some operations)
    convert n to int(element of NG)
    use n as int

I tried to Play around with range/len but I didnt come to a solution.

Edit2:

This is what I have:

import pandas as pd
import matplotlib.pyplot as plt

NG = ['A','B','C']

l = [1,2,3,4,5,6]
b = [6,5,4,3,2,1]

for n in NG:
    print(n)
    dflist = []
    df = pd.DataFrame(l)
    dflist.append(df)
    df2 = pd.DataFrame(b)
    dflist.append(df2)
    df = pd.concat(dflist, axis = 1)
    df.plot()

The Output are 3 figures that look like this: enter image description here

But I want them to be in one figure:

import pandas as pd
import matplotlib.pyplot as plt

NG = ['A','B','C']

l = [1,2,3,4,5,6]
b = [6,5,4,3,2,1]

for n in NG:
    print(n)
    dflist = []
    df = pd.DataFrame(l)
    dflist.append(df)
    df2 = pd.DataFrame(b)
    dflist.append(df2)
    df = pd.concat(dflist, axis = 1)
    ax = plt.subplot(6, 2, n + 1)
    df.plot(ax = ax)

This code works, but only if the list NG is made out of integers [1,2,3]. But I have it in strings. And I Need them in the Loop.

Artur Müller Romanov
  • 4,417
  • 10
  • 73
  • 132

4 Answers4

1

Here is my 2 cents:

>>> for n in l:
...     print ord(n)
...     print n
... 
65
A
66
B
67
C

To convert back to char

>>> chr(65)
'A'
Devidas
  • 2,479
  • 9
  • 24
1

How to access both the element of list and its index?

That is the real question as I understood mainly from this comment. And it is a pretty common and straightforward piece of code:

NG = ['A', 'B', 'C']

for i in range(len(NG)):
    print(i)
    print(NG[i])
Jeyekomon
  • 2,878
  • 2
  • 27
  • 37
0

I think integer mean here is ascii value of character so you can use again your ascii value to play with characters my solution is you have to type cast your variables like this , and use ord() function to get ascii values

l = ['A','B','C']
for i in range(0,len(l)):
    print("string value is ",l[i])
    # now for integer values
    if type(l[i]) != 'int':
        print("ascii value of this char is ",ord(l[i]))
    else:
        print("already int type go on..")

as because there is no meaning of having a int value of characters , int value of character generally refers as ascii value may be some other formats

0

Use enumerate to iterate both on the indices and the letters.

NG = ['A','B','C']

for i, n in enumerate(NG, 1):
    print(i, n)

Will output:

(1, 'A')
(2, 'B')
(3, 'C')

In your case, because you don't need the letters at all in your loop, you can use the underscore _ to notify coders in your future about what your code do - it uses the len of NG just for the indices.

for i, _ in enumerate(NG, 1):
Kruupös
  • 5,097
  • 3
  • 27
  • 43