如何在两个相邻数字之间插入数字?

时间:2018-06-17 19:48:40

标签: python arrays python-3.x

你如何 1)在任何两个相邻的5之间插入1?然后 2)在第二个列表中插入一个与插入第一个列表的索引相同的索引?

例如,

list1 = [  5,   1,   5,   5,   5,   1,  etc.] 

会变成

list1 = [  5,   1,   5,   1,   5,   1,   5,   1,  etc.]

list2 = [ val, val, val, val, val, val, etc.] 

会变成

list2 = [ val, val, val, Nval, val, Nval, etc.]

(Nval高于=增值)

我是初学者,所以非常感谢帮助:O)

5 个答案:

答案 0 :(得分:2)

您需要查看成对的连续值。为此,我们将列表与最后一个项目(list[:-1])配对,再次列表,但第一个项目被切断(list[1:])。 (此处使用的切片表示法是being introduced in the official Python tutorial,并解释为in this answer。)

zip(list1[:-1], list1[1:])

zip函数将一对序列转换为一对序列,并引入here in the tutorialdocumented here。)

让我们看看这些对是(5, 5)

[pair == (5, 5) for pair in zip(list1[:-1], list1[1:])]

此处使用的功能是list comprehension,这是一种通过给出从现有可迭代构造它的规则来编写(新)列表的方法。

这些对的指数是多少?让我们用enumerate编号:

[n for (n, pair) in enumerate(zip(list1[:-1], list1[1:])) if pair == (5, 5)]

这是另一个列表理解,这次是元素的条件(“谓词”)。请注意enumerate返回数字和值对(这是我们的原始对),并且我们使用隐式解包将它们分别放入循环变量npair

list.insert(i, new_value)获取之后的索引,其中应插入新值。因此,要找到插入原始列表(以及列表2)的位置,我们需要将1添加到对索引中:

idxs = [n + 1 for (n, pair) in enumerate(zip(list1[:-1], list1[1:])) if pair == (5, 5)]

for i in reversed(idxs):
    list1.insert(idxs, 1)
    list2.insert(idxs, 'Nval')

(我们以相反的顺序插入,以便不移动我们尚未插入的对。)

答案 1 :(得分:1)

您可以使用单个列表推导来恢复插入索引。您正在寻找i的索引5 == list1[i-1] == list1[i]

然后,您需要按索引的降序插入。

list1 = [5,   1,   5,   5,   5,   1]
list2 = [val, val, val, val, val, val] 

indices = [i for i in range(1, len(list1)) if 5 == list1[i-1] == list1[i]]

for i in reversed(indices):
    list1.insert(i, 1)
    list2.insert(i, Nval)

print(list1) # [5, 1, 5, 1, 5, 1, 5, 1]
print(list2) # [val, val, val, Nval, val, Nval, val, val]

答案 2 :(得分:0)

您可以使用itertools.groupby

import itertools
list1 = [5, 1, 5, 5, 5, 1]
copied = iter(['val' for _ in list1])
grouped = [[a, list(b)] for a, b in itertools.groupby(list1)]
new_result = [list(b) if a != 5 else [[5, 1] if c < len(b) - 1 else [5] for c, _ in enumerate(b)] for a, b in grouped]
final_result = [[i] if not isinstance(i, list) else i for b in new_result for i in b]
new_copied = [[next(copied)] if len(i) == 1 else [next(copied), 'Nval'] for i in final_result]
list2, list2_copied = list(itertools.chain(*final_result)), list(itertools.chain(*new_copied))

输出:

[5, 1, 5, 1, 5, 1, 5, 1]
['val', 'val', 'val', 'Nval', 'val', 'Nval', 'val', 'val']

答案 3 :(得分:0)

templist [5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1]
list2 [5, 1, 5, 42, 5, 42, 5, 1, 5, 42, 5, 1, 5, 42, 5, 42, 5, 42]

给我输出:

list1 = templist

结束: import React, { Component } from 'react'; import * as firebase from 'firebase'; const userList = [] class SignUpForm extends Component { constructor() { super(); /*initialize my state*/ } //get the user list from the database componentWillMount() { const users = database.ref('users') users.once('child_added', snapshot => { userList.push(snapshot.val()) }) } /*functions that get username from input and store into the state*/ validateForm() { //in this.state, 'username' is the text input that the user entered const { username } = this.state //this is the function that checks if the username is already in use const findUsername = (username) => { userList.map(user => { if (user.username === username) { console.log("test") return true } }) } //if username has been taken if (findUsername(username)) { console.log("found the same username in the database") } /*other validation checks*/ } render() { return( <div> {/*input elements, etc*/} <button onClick={this.validateForm} </div> ) } }

答案 4 :(得分:0)

基于public static List<int> AllIndexesOf(this string str, string value) { if (String.IsNullOrEmpty(value)) throw new ArgumentException("the string to find may not be empty", "value"); List<int> indexes = new List<int>(); for (int index = 0; ; index += value.Length) { index = str.IndexOf(value, index); if (index == -1) return indexes; indexes.Add(index); } } zip的单行解决方案:

reduce