如何在python 3中从for inside for循环中增加迭代器?

时间:2015-08-28 21:35:10

标签: python python-3.x for-loop iterator

for i in range (0, 81):
    output = send command
    while True:
        last_byte = last_byte - offset
    if last_byte > offset:
       output = send command
       i+
    else:
        output = send command
        i+
        break

我想在每次执行send命令时增加迭代器。现在它只在执行for循环时增加1。请指教

for i in range(0,10):
    print(i)
    i +=2
    print("increased i", i)

我运行了这段代码,它从0到9生成。我原以为它会将迭代器增加2。

7 个答案:

答案 0 :(得分:12)

将迭代器的副本保存为命名对象。然后,如果您愿意,可以跳过。

>>> myiter = iter(range(0, 10))
>>> for i in myiter:
    print(i)
    next(myiter, None)
...
0
2
4
6
8

答案 1 :(得分:5)

您无法在for循环中执行此操作。因为每次循环重新启动时,它都会重新分配变量i(即使在循环中更改它之后),并且每次只增加重新分配的变量。如果你想做这样的事情,你最好使用while循环并手动增加一次性变量。

>>> i=0
>>> while i< 10 :
...     print(i)
...     i +=2
...     print("increased i", i)
... 
0
('increased i', 2)
2
('increased i', 4)
4
('increased i', 6)
6
('increased i', 8)
8
('increased i', 10)

除此之外,如果你想在一个句点上增加变量而不是基于某个特定条件,你可以使用适当的切片器来切片你循环的迭代。

例如,如果你有一个迭代器,你可以使用itertools.islice()如果你有一个列表,你只需在索引时使用步骤(my_list[start:end:step])。

答案 2 :(得分:2)

range()有一个可选的第三个参数来指定步骤。用它来将计数器增加2。例如:

for i in range(0, 10, 2):
    print(i)
    print("increased i", i)

你不能像普通变量一样增加i的原因是因为当for循环开始执行时,会创建一个列表(或Python 3+中的范围对象),i仅以递增方式表示该对象中的每个值。

答案 3 :(得分:1)

@ilaunchpad对不起,我知道发布此内容为时已晚,但这就是您要找的内容

i=0
for J    in range(0,10):
    print(i)
    i = i + 2
print("increased i", i)

您不应在For语句中使用相同的变量。

Output
vaibhav@vaibhav-Lenovo-G570:~$ python3 /home/vaibhav/Desktop/Python/pattern_test.py
0
2
4
6
8
10
12
14
16
18
increased i 20

答案 4 :(得分:0)

怎么样?

for i in range(10):
     if i == 3:
         i += 1
         continue
     print(i)

只需添加继续,计数器就会增加-打印结果为:

0
1
2
4
5
6
7
8
9

请注意,如果没有继续,则4将被打印两次。 我认为这可以回答问题。

答案 5 :(得分:0)

由于没有允许使用下一个迭代器结果的答案,这是我建议的解决方案,它通过使用 enumerate() 函数或仅使用 iter()功能:

x = [1, True, 3, '4', 5.05, 6, 7, 8, 9, 10]
x_enum = enumerate(x)
for idx, elem in x_enum:
    if idx == 1: # Example condition to catch the element, where we want to iterate manually
        print('$: {}'.format(elem))
        idx, elem = next(x_enum)
        print('$: {}'.format(elem))
    else:
        print(elem)

将打印:

1
$: True        # As you can see, we are in the if block
$: 3           # This is the second print statement, which uses the result of next()
4
5.05
6
7
8
9
10

这也可以通过简单的迭代器实现:

x_iter = iter(x)
for elem in x_iter:
    if elem == '4': # Example condition to catch the element, where we want to iterate manually
        print('$: {}'.format(elem))
        elem = next(x_iter)
        print('$: {}'.format(elem))
    else:
        print(elem)

答案 6 :(得分:-1)

我写了这样的东西。

library(shiny)
library(formattable)
library(htmlwidgets)


#This is the part that could be added to formattable to allow shiny integration. Not sure about height 100% but the function wont accept NULL
formattableOutput <- function(outputId, width = "100%", height = "100%") {
  shinyWidgetOutput(outputId, "formattable_widget", width, height, package = "formattable")
}

renderFormattable <- function(expr, env = parent.frame(), quoted = FALSE) {
  if (!quoted) { expr <- substitute(expr) } # force quoted
  shinyRenderWidget(expr, formattableOutput, env, quoted = TRUE)
}

#Define a dataframe (example stolen from formattable readme)
df <- data.frame(
  id = 1:10,
  name = c("Bob", "Ashley", "James", "David", "Jenny", 
           "Hans", "Leo", "John", "Emily", "Lee"), 
  age = c(28, 27, 30, 28, 29, 29, 27, 27, 31, 30),
  grade = c("C", "A", "A", "C", "B", "B", "B", "A", "C", "C"),
  test1_score = c(8.9, 9.5, 9.6, 8.9, 9.1, 9.3, 9.3, 9.9, 8.5, 8.6),
  test2_score = c(9.1, 9.1, 9.2, 9.1, 8.9, 8.5, 9.2, 9.3, 9.1, 8.8),
  final_score = c(9, 9.3, 9.4, 9, 9, 8.9, 9.25, 9.6, 8.8, 8.7),
  registered = c(TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE),
  stringsAsFactors = FALSE)


##################################
# Shiny server
##################################

server <- function(input, output) {

  #use our new function to create an output called formattableexample. We require an explicit call to the as.htmlwidget function as this does not register as an interactive  environment

  output$formattableexample <- renderFormattable({
    as.htmlwidget(
      formattable(df, list(
        age = color_tile("white", "orange"),
        grade = formatter("span",
                          style = x ~ ifelse(x == "A", style(color = "green", font.weight = "bold"), NA)),
        test1_score = color_bar("pink"),
        test2_score = color_bar("pink"),
        final_score = formatter("span",
                                style = x ~ style(color = ifelse(rank(-x) <= 3, "green", "gray")),
                                x ~ sprintf("%.2f (rank: %02d)", x, rank(-x))),
        registered = formatter("span", 
                               style = x ~ style(color = ifelse(x, "green", "red")),
                               x ~ icontext(ifelse(x, "ok", "remove"), ifelse(x, "Yes", "No")))
      ))

    )
  })
}

##################################
# Shiny ui
##################################
ui <- fluidPage(
  #use our new function to show the output we just defined. 

  fluidRow(
     box(
      formattableOutput("formattableexample")
    ),
  )
)

shinyApp(ui = ui, server = server)

现在我有一个完全控制,但背景是我必须检查所有条件。