如何使用 Python 在一个单元格中读取逗号分隔的字符串

How to read comma separated string in one cell using Python

我有一个项目,您需要从 excel 文件中读取数据。我使用 openpyxl 来读取上述文件。在将数据转换为整数之前,我尝试先将数据读取为字符串;但是,我认为,由于一个单元格中的数字用逗号分隔,所以发生了错误。我正在尝试做一个嵌套列表,但我仍然是 Python.

中的新手

我的代码如下所示:

# storing S
S_follow = []
for row in range(2, max_row+1):
  if (sheet.cell(row,3).value is not None):
  S_follow.append(sheet.cell(row, 3).value);
# to convert the list from string to int, nested list
for i in range(0, len(S_follow)):
S_follow[i] = int(S_follow[i])
print(S_follow)

我试图读取的数据是: ['2,3', 4, '5,6', 8, 7, 9, 8, 9, 3, 11, 0]

希望得到您的帮助

S_follow =  ['2,3', 4, '5,6', 8, 7, 9, 8, 9, 3, 11, 0]
for i in range(0, len(S_follow)):
    try:
        s = S_follow[i].split(',')
        del S_follow[i]
        for j in range(len(s)):
            s[j] = int(s[j])
        S_follow.insert(i,s)
    except AttributeError as e:
        S_follow[i] = int(S_follow[i])
print(S_follow)

当您要在脚本倒数第二行的循环中将值转换为整数时,您可以检查每个值是整数还是字符串,如果是字符串,则将其拆分,将拆分值转换为整数并将它们推送到名为 strVal 的临时列表,然后将该临时列表附加到名为 S_follow_int 的新列表。但如果该值不是字符串,则只需将它们附加到 S_follow_int 而不做任何事情。

data= ['2,3', 4, '5,6', 8, 7, 9, 8, 9, 3, 11, 0]
S_follow = []
S_follow_int = []

for row in range(0, len(data)):
  if (sheet.cell(row,3).value is not None):
      S_follow.append(sheet.cell(row, 3).value);
      
# to convert the list from string to int, nested list
for i in range(0, len(S_follow)):
    
    #if the current value is a string, split it, convert the values to integers, put them on a temp list called strVal and then append it to S_follow_int
    if type(S_follow[i]) is str:
        x = S_follow[i].split(',')
        strVal = []
        for y in x:
            strVal.append(int(y))
        S_follow_int.append(strVal)
        
    #else if it is already an integer, just append it to S_follow_int without doing anything

    else:
        S_follow_int.append(S_follow[i])
    
print(S_follow_int)

但是,我建议您检查用于从 excel 文件本身检索数据的初始循环中每个值的数据类型 (str/int),而不是将所有值推送到S_follow 然后像这样转换类型:

#simplified representation of the logic you can use for your script

data = ['2,3', 4, '5,6', 8, 7, 9, 8, 9, 3, 11, 0]
x = []

for dat in data:
    if dat is not None:
        if type(dat) is str:
            y = dat.split(',')
            strVal = []
            for z in y:
                strVal.append(int(z))
            x.append(strVal)
        else:
            x.append(dat)
print(x)