我试图在Python
中创建一个list
,其中包含从活动excel
表中提取的值。我希望它从excel文件中提取step#值并将其附加到列表中,同时还包括该元素的编号。例如,1_1
第一次拉1,1_2
第二次,1_3
第三次,等等。我的代码如下。。。你知道吗
import win32com.client
xl = win32com.client.Dispatch("Excel.Application")
CellNum = xl.ActiveSheet.UsedRange.Rows.Count
Steps = []
for i in range(2,CellNum + 1): #Create load and step arrays in abaqus after importing from excel
if str(int(xl.Cells(i,1).value))+('_1' or '_2' or '_3' or '_4' or '_5' or '_6') in Steps:
StepCount = 1
for x in Steps:
if x == str(int(xl.Cells(i,1).value))+('_1' or '_2' or '_3' or '_4' or '_5' or '_6'):
StepCount+=1
Steps.append(str(int(xl.Cells(i,1).value))+'_'+str(StepCount))
else:
Steps.append(str(int(xl.Cells(i,1).value))+'_1')
我知道如果没有excel文件,这个程序将不能为你们任何人运行,但我只是想知道这是不是我遗漏了一些简单的错误。当我运行这个时,StepCount不会超过2,所以我会收到一堆1\u2、2\u2、3\u2等元素。我已经把结果列表贴在下面了。你知道吗
>>> Steps
['1_1', '2_1', '3_1', '4_1', '5_1', '6_1', '7_1', '8_1', '9_1', '10_1', '11_1', '12_1',
'13_1', '14_1', '1_2', '14_2', '13_2', '12_2', '11_2', '10_2', '2_2', '3_2', '9_2',
'8_2', '7_2', '6_2', '5_2', '4_2', '3_2', '2_2', '1_2', '2_2', '3_2', '4_2', '5_2',
'6_2', '7_2', '8_2', '9_2', '10_2', '11_2', '12_2', '13_2', '14_2', '1_2', '2_2']
编辑#1:那么,如果('_1' or '_2' or '_3' or '_4' or '_5' or '_6')
总是只使用#1,是这行代码弄乱了我的计数器吗?你知道吗
if x == str(int(xl.Cells(i,1).value))+('_1' or '_2' or '_3' or '_4' or '_5' or '_6'):
因为它只使用_1
,所以它只计算1_1
,而不检查1_2, 1_3, 1_4, etc
编辑#2:现在我使用以下代码。我的输入列表也在下面。你知道吗
from collections import defaultdict
StepsList = []
Steps = []
tracker = defaultdict(int)
for i in range(2,CellNum + 1):
StepsList.append(int(xl.Cells(i,1).value))
>>> StepsList
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1, 14, 13, 12, 11, 10, 2, 3, 9, 8,
7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1, 2]
for cell in StepsList:
Steps.append('{}_{}'.format(cell, tracker[cell]+1)) # This is +1 because the tracker starts at 0
tracker[cell]+=1
我得到以下错误:ValueError: zero length field name in format
来自for cell in StepsList:
迭代块
编辑#3:开始工作。因为某种原因它不喜欢
Steps.append('{}_{}'.format(cell, tracker[cell]+1))
所以我把它改成了
for cell in StepsList:
tracker[cell]+=1
Steps.append(str(cell)+'_'+str(tracker[cell]))
谢谢你的帮助!你知道吗
这条线:
不会做你想做的事。
('_1' or '_2' or '_3' or '_4' or '_5' or '_6')
将始终返回'_1'
。它不会遍历一系列or
值来寻找匹配项。你知道吗如果看不到预期的输入和预期的输出,就很难指出正确的方向来真正从代码中获得所需的内容,但很可能您希望利用^{} 或
itertools
中的其他组合方法之一。你知道吗更新
根据你的意见,我认为这是解决你问题的一种方法。假设输入列表包含以下内容:
您可以执行以下操作:
结果:
使用
itertools
的组合可能有更有效的方法,但这种方法肯定是最直接的相关问题 更多 >
编程相关推荐