Python 为什么赢了';列表删除功能是否删除空格?
我正在使用Python 为什么赢了';列表删除功能是否删除空格?,python,list,python-3.x,for-loop,Python,List,Python 3.x,For Loop,我正在使用re.split生成单词和空格的列表: string = "hello world i'm a new program" words_length = [] length = 21 因此: 但我想要的是: line = "helloworldi'manew" words = [' ', ' ', ' ', ' ', ' ', 'program'] 我如何才能做到这一点?您正在跳过索引,因为您正在从列表中删除字符 每次删除一个字符时,该字符右侧的所有内容都会向上向左移动一步,其索引也
re.split
生成单词和空格的列表:
string = "hello world i'm a new program"
words_length = []
length = 21
因此:
但我想要的是:
line = "helloworldi'manew"
words = [' ', ' ', ' ', ' ', ' ', 'program']
我如何才能做到这一点?您正在跳过索引,因为您正在从列表中删除字符
每次删除一个字符时,该字符右侧的所有内容都会向上向左移动一步,其索引也会向下移动一步。但是您的x
索引仍然会上升1,因此现在您正在引用列表中的后面一个元素:
line = "hello world i'm a new"
words = ['program']
x == 0
words == ['hello', ' ', 'world', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program']
# 0 1 2 3 4 5 ...
words[x] == 'hello'
del words[x]
words == [' ', 'world', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program']
# 0 1 2 3 4 5 ...
x == 1
words == [' ', 'world', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program']
# 0 1 2 3 4 5 ...
words[x] == 'world'
del words[x]
words == [' ', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program']
# 0 1 2 3 4 5 ...
x == 2
words == [' ', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program']
# 0 1 2 3 4 5 ...
words[x] == 'i'
del words[x]
words == [' ', ' ', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program']
# 0 1 2 3 4 5 ...
或者,您可以删除单词(为了提高效率,从相反的列表中删除),但随后使用while
循环并测试累积长度:
line = []
current_length = 0
for i, word in enumerate(words):
current_length += len(word)
if current_length > length:
i -= 1
break
line.append(word)
# here i is the index of the last element of words actually used
words = words[i + 1:] # remove the elements that were used.
line = ''.join(line)
但是,如果您试图将行长度包装应用于Python字符串,则可以通过使用。它可以轻松地在最大长度内进行换行:
line = []
current_length = 0
reversed_words = words[::-1]
while reversed_words:
l = len(reversed_words[-1])
if current_length + l > length:
break
line.append(reversed_words.pop())
current_length += l
words = reversed_words[::-1]
line = ''.join(line)
您正在跳过索引。试着用
[''a',''b','']
看看这与空格无关。另外,字母的长度和长度是什么?在迭代时修改序列通常是个坏主意。我有一个用re.split('\w',string)构建的单词列表-我想你应该从这里开始-这不是一个单词列表-那完全不同…@NathanSchwarz:你的例子暗示了他们是;在只包含单个字符的输入样本中,以及在变量字母的使用中。
line = []
current_length = 0
for i, word in enumerate(words):
current_length += len(word)
if current_length > length:
i -= 1
break
line.append(word)
# here i is the index of the last element of words actually used
words = words[i + 1:] # remove the elements that were used.
line = ''.join(line)
line = []
current_length = 0
reversed_words = words[::-1]
while reversed_words:
l = len(reversed_words[-1])
if current_length + l > length:
break
line.append(reversed_words.pop())
current_length += l
words = reversed_words[::-1]
line = ''.join(line)
wrapped = textwrap.fill(string, length)