如何在列表中分别从列表中获取值[关闭] 。

问题描述 投票:-3回答:1

我有一个项目是这样的。

follow_act = [[2, 3], 4, [5, 6], 8, 7, 9, 8, 10, 10, 11] 

我读取follow_act的代码是:

follow = []
follow_act = []
for row in range(2, max_row):
    if sheet.cell(row, 3).value is not None:
        follow.append(sheet.cell(row, 3).value)

# to convert the list from string to int, nested list
for i in range(0, len(follow)):
# if the current value is a string, split it
# convert the values to integers
# put them on a temp list called strVal
# then append it to follow_act
    if type(follow[i]) is str:
        z = follow[i].split(',')
        strVal = []
        for y in z:
            strVal.append(int(y))
        s_follow_int.append(strVal)

# else if it is already an integer
# just append it to follow_act without doing anything
else:
    follow_act.append(follow[i])

现在,在我代码的后半部分, 我试图调用 follow_act[2] 也就是 [5, 6] 并把它们放在一个for循环中,只是为了分别得到列表中的数字。

For itm in follow_act[2]:
  print(itm)

输出的结果是这样的 [5, 6].

预期产出为 5 然后 6.

在我的代码中,数字在 follow_actintegers. 因为当我试图从excel文件中读取数值时,它被读取为字符串,所以我将它们转换为整数。

EDIT: 当我尝试调用 follow_act[2] 在for循环之前,我得到了这样的东西。[[5, 6]]

我使用的代码是用来获取特定项目的 follow_act 是。

activity = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
select_act = [3]
follow_act = [d for a, d in zip(activity, follow) if a in select_act]

因为我想用我的代码来获取select_act中活动的follow_act。对于这种情况,即使没有显示,也应该是5和6。

任何帮助建议将被感激! 谢谢!我的项目是这样的

python python-3.x nested-lists
1个回答
1
投票

这是你的代码吗?

follow =  ['2,3', 4, '5,6', 8, 7, 9, 8, 10, 10, 11]
activity = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
select_act = [3]
follow_act = [d for a, d in zip(activity, follow) if a in select_act]
print(type(follow_act[0]))
for itm in follow_act:
  print(itm)

如果是,那么

print(type(follow_act[0]))

返回 "<class 'str'>"

print(follow_act)

返回 ['5,6']

print(follow_act[0])

返回 5,6

所以很明显,它是把follow_act里面的内容当作一个字符串。

如果它是正确的,那么完美的,否则评论,以便我们可以检查解决方案。 :)

© www.soinside.com 2019 - 2024. All rights reserved.