在操作列表或字符串时,最有效的迭代方法是什么?

时间:2020-04-03 15:31:47

标签: python python-3.x list

我的目标是在python中创建一个代码破坏者。到目前为止,我已经弄乱了字母,结果得到了各个字符的列表。

#Result of inputting the string 'hello world'
['C', 'V', 'N', 'N', 'H', 'X', 'H', 'K', 'N', 'O']

我的目标是将其输出为带有空格“ CVNNH XHKNO”的字符串

现在我有几种选择,但是我不确定哪一种最好: 我要先将其转换为字符串,然后再进行操作,还是先处理列表,再转换为字符串?

到目前为止,我已经从该过程中自动获得了以下帮助程序

length = [5,5] #list
total_chars = 10 #int
no_of_words = 2 #int

我将其转换为字符串CVNNHXHKNO,并考虑通过计算起点[0],中点[5]和终点[11]在第5个字母后插入空格。

start = 0
mid_point = total_chars - length[0]

print(mid_point)
first_word = message[start:mid_point]
print(first_word)

second_word = message[mid_point:total_chars]
print(second_word)

completed_word = first_word + ' ' + second_word
print(completed_word)

不幸的是,这只是手动操作,如果有5个或更多的单词,则不会考虑。我曾尝试使用列表长度在嵌套for循环中遍历单个字符的原始列表,但似乎使自己困惑并思考过多。

5 个答案:

答案 0 :(得分:2)

如果您将此作为输入:

l = ['C', 'V', 'N', 'N', 'H', 'X', 'H', 'K', 'N', 'O']
length = [5,5] #list
total_chars = 10 #int
no_of_words = 2 #int

然后您可以按以下方式计算输出:

words = []
pos = 0
for i in length:
  words.append("".join(l[pos:pos+i]))
  pos += i

result = " ".join(words)

print(words)
print(result)

输出:

['CVNNH', 'XHKNO']
CVNNH XHKNO

答案 1 :(得分:2)

我不太了解您的问题,但是可能您想要的是类似的

letters = ['C', 'V', 'N', 'N', 'H', 'X', 'H', 'K', 'N', 'O']
length = [5, 5]
words = []
offset = 0

for i in length:
    words.append(''.join(letters[offset:offset+i]))
    offset += i   

string_words = ' '.join(words)
print(string_words)

答案 2 :(得分:1)

lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

WORD_SIZE = 5
NUM_WORDS = 2  # You could replace this with `len(lst) / WORD_SIZE`
result = ' '.join(
  ''.join(
    lst[i * WORD_SIZE: i * WORD_SIZE + 5]
  )
  for i in range(NUM_WORDS)
)

#  result = 'abcde fghij'

答案 3 :(得分:1)

要使用无限长的长度列表作为输入,可以遍历length列表并加入相应的字母:

letters = ["A", "S", "I", "M", "P", "L", "E", "T", "E", "S", "T"]
length = [1, 6, 4]

starting_index = 0
for l in length:
    print("".join(letters[starting_index:starting_index+l]))
    starting_index += l

答案 4 :(得分:1)

您似乎只需要在length列表中描述每个单词中有多少个字母:

message = ['C', 'V', 'N', 'N', 'H', 'X', 'H', 'K', 'N', 'O']

length = [5,5]

offset = 0
words = []
for size in length:
    words.append(''.join(message[offset:offset+size]))
    offset += size
completed_word = ' '.join(words)

print(completed_word)

输出:

CVNNH XHKNO
相关问题