使用list的元素作为字符串和整数

时间:2018-04-09 07:04:14

标签: python string loops integer

有没有办法首先将字符串列表的元素用作字符串,然后再用作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

我尝试使用range / len,但我没有找到解决方案。

EDIT2:

这就是我所拥有的:

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()

输出是3个数字,如下所示: enter image description here

但我希望他们在一个人物中:

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)

此代码有效,但仅当列表NG由整数[1,2,3]构成时才有效。但我在strings中有它。我需要它们在循环中。

4 个答案:

答案 0 :(得分:1)

这是我的2美分:

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

转换回char

>>> chr(65)
'A'

答案 1 :(得分:1)

如何访问列表元素及其索引?

这是我真正理解的真正问题,主要来自this comment。这是一个非常常见且简单的代码:

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

for i in range(len(NG)):
    print(i)
    print(NG[i])

答案 2 :(得分:0)

我认为这里的整数意思是字符的ascii值 所以你可以再次使用你的ascii值来玩角色 我的解决方案是你必须像这样输入你的变量, 并使用 ord()函数获取ascii值

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..")

因为没有字符的int值的意思,字符的int值一般指ascii值可能是其他一些格式

答案 3 :(得分:0)

使用enumerate迭代索引和字母。

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

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

将输出:

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

在您的情况下,因为您在循环中根本不需要这些字母,所以您可以使用下划线_通知编码员您将来的代码所做的事情 - 它使用len NG仅适用于指数。

for i, _ in enumerate(NG, 1):